text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class PestoDemo extends StatelessWidget {
const PestoDemo({ super.key });
static const String routeName = '/pesto';
@override
Widget build(BuildContext context) => const PestoHome();
}
const String _kSmallLogoImage = 'logos/pesto/logo_small.png';
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
const double _kAppBarHeight = 128.0;
const double _kFabHalfSize = 28.0; // TODO(mpcomplete): needs to adapt to screen size
const double _kRecipePageMaxWidth = 500.0;
final Set<Recipe?> _favoriteRecipes = <Recipe?>{};
final ThemeData _kTheme = ThemeData(
appBarTheme: const AppBarTheme(foregroundColor: Colors.white, backgroundColor: Colors.teal),
brightness: Brightness.light,
floatingActionButtonTheme: const FloatingActionButtonThemeData(foregroundColor: Colors.white),
);
class PestoHome extends StatelessWidget {
const PestoHome({super.key});
@override
Widget build(BuildContext context) {
return const RecipeGridPage(recipes: kPestoRecipes);
}
}
class PestoFavorites extends StatelessWidget {
const PestoFavorites({super.key});
@override
Widget build(BuildContext context) {
return RecipeGridPage(recipes: _favoriteRecipes.toList());
}
}
class PestoStyle extends TextStyle {
const PestoStyle({
double super.fontSize = 12.0,
super.fontWeight,
Color super.color = Colors.black87,
super.letterSpacing,
super.height,
}) : super(
inherit: false,
fontFamily: 'Raleway',
textBaseline: TextBaseline.alphabetic,
);
}
// Displays a grid of recipe cards.
class RecipeGridPage extends StatefulWidget {
const RecipeGridPage({ super.key, this.recipes });
final List<Recipe?>? recipes;
@override
State<RecipeGridPage> createState() => _RecipeGridPageState();
}
class _RecipeGridPageState extends State<RecipeGridPage> {
@override
Widget build(BuildContext context) {
final double statusBarHeight = MediaQuery.of(context).padding.top;
return Theme(
data: _kTheme.copyWith(platform: Theme.of(context).platform),
child: Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.redAccent,
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Not supported.'),
));
},
child: const Icon(Icons.edit),
),
body: CustomScrollView(
semanticChildCount: widget.recipes!.length,
slivers: <Widget>[
_buildAppBar(context, statusBarHeight),
_buildBody(context, statusBarHeight),
],
),
),
);
}
Widget _buildAppBar(BuildContext context, double statusBarHeight) {
return SliverAppBar(
pinned: true,
expandedHeight: _kAppBarHeight,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.search),
tooltip: 'Search',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Not supported.'),
));
},
),
],
flexibleSpace: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size size = constraints.biggest;
final double appBarHeight = size.height - statusBarHeight;
final double t = (appBarHeight - kToolbarHeight) / (_kAppBarHeight - kToolbarHeight);
final double extraPadding = Tween<double>(begin: 10.0, end: 24.0).transform(t);
final double logoHeight = appBarHeight - 1.5 * extraPadding;
return Padding(
padding: EdgeInsets.only(
top: statusBarHeight + 0.5 * extraPadding,
bottom: extraPadding,
),
child: Center(
child: PestoLogo(height: logoHeight, t: t.clamp(0.0, 1.0)),
),
);
},
),
);
}
Widget _buildBody(BuildContext context, double statusBarHeight) {
final EdgeInsets mediaPadding = MediaQuery.of(context).padding;
final EdgeInsets padding = EdgeInsets.only(
top: 8.0,
left: 8.0 + mediaPadding.left,
right: 8.0 + mediaPadding.right,
bottom: 8.0,
);
return SliverPadding(
padding: padding,
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _kRecipePageMaxWidth,
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final Recipe? recipe = widget.recipes![index];
return RecipeCard(
recipe: recipe,
onTap: () { showRecipePage(context, recipe); },
);
},
childCount: widget.recipes!.length,
),
),
);
}
void showFavoritesPage(BuildContext context) {
Navigator.push(context, MaterialPageRoute<void>(
settings: const RouteSettings(name: '/pesto/favorites'),
builder: (BuildContext context) => const PestoFavorites(),
));
}
void showRecipePage(BuildContext context, Recipe? recipe) {
Navigator.push(context, MaterialPageRoute<void>(
settings: const RouteSettings(name: '/pesto/recipe'),
builder: (BuildContext context) {
return Theme(
data: _kTheme.copyWith(platform: Theme.of(context).platform),
child: RecipePage(recipe: recipe),
);
},
));
}
}
class PestoLogo extends StatefulWidget {
const PestoLogo({super.key, this.height, this.t});
final double? height;
final double? t;
@override
State<PestoLogo> createState() => _PestoLogoState();
}
class _PestoLogoState extends State<PestoLogo> {
// Native sizes for logo and its image/text components.
static const double kLogoHeight = 162.0;
static const double kLogoWidth = 220.0;
static const double kImageHeight = 108.0;
static const double kTextHeight = 48.0;
final TextStyle titleStyle = const PestoStyle(fontSize: kTextHeight, fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 3.0);
final RectTween _textRectTween = RectTween(
begin: const Rect.fromLTWH(0.0, kLogoHeight, kLogoWidth, kTextHeight),
end: const Rect.fromLTWH(0.0, kImageHeight, kLogoWidth, kTextHeight),
);
final Curve _textOpacity = const Interval(0.4, 1.0, curve: Curves.easeInOut);
final RectTween _imageRectTween = RectTween(
begin: const Rect.fromLTWH(0.0, 0.0, kLogoWidth, kLogoHeight),
end: const Rect.fromLTWH(0.0, 0.0, kLogoWidth, kImageHeight),
);
@override
Widget build(BuildContext context) {
return Semantics(
namesRoute: true,
child: Transform(
transform: Matrix4.identity()..scale(widget.height! / kLogoHeight),
alignment: Alignment.topCenter,
child: SizedBox(
width: kLogoWidth,
child: Stack(
clipBehavior: Clip.none,
children: <Widget>[
Positioned.fromRect(
rect: _imageRectTween.lerp(widget.t!)!,
child: Image.asset(
_kSmallLogoImage,
package: _kGalleryAssetsPackage,
fit: BoxFit.contain,
),
),
Positioned.fromRect(
rect: _textRectTween.lerp(widget.t!)!,
child: Opacity(
opacity: _textOpacity.transform(widget.t!),
child: Text('PESTO', style: titleStyle, textAlign: TextAlign.center),
),
),
],
),
),
),
);
}
}
// A card with the recipe's image, author, and title.
class RecipeCard extends StatelessWidget {
const RecipeCard({ super.key, this.recipe, this.onTap });
final Recipe? recipe;
final VoidCallback? onTap;
TextStyle get titleStyle => const PestoStyle(fontSize: 24.0, fontWeight: FontWeight.w600);
TextStyle get authorStyle => const PestoStyle(fontWeight: FontWeight.w500, color: Colors.black54);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Hero(
tag: 'packages/$_kGalleryAssetsPackage/${recipe!.imagePath}',
child: AspectRatio(
aspectRatio: 4.0 / 3.0,
child: Image.asset(
recipe!.imagePath!,
package: recipe!.imagePackage,
fit: BoxFit.cover,
semanticLabel: recipe!.name,
),
),
),
Expanded(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Image.asset(
recipe!.ingredientsImagePath!,
package: recipe!.ingredientsImagePackage,
width: 48.0,
height: 48.0,
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(recipe!.name!, style: titleStyle, softWrap: false, overflow: TextOverflow.ellipsis),
Text(recipe!.author!, style: authorStyle),
],
),
),
],
),
),
],
),
),
);
}
}
// Displays one recipe. Includes the recipe sheet with a background image.
class RecipePage extends StatefulWidget {
const RecipePage({ super.key, this.recipe });
final Recipe? recipe;
@override
State<RecipePage> createState() => _RecipePageState();
}
class _RecipePageState extends State<RecipePage> {
final TextStyle menuItemStyle = const PestoStyle(fontSize: 15.0, color: Colors.black54, height: 24.0/15.0);
double _getAppBarHeight(BuildContext context) => MediaQuery.of(context).size.height * 0.3;
@override
Widget build(BuildContext context) {
// The full page content with the recipe's image behind it. This
// adjusts based on the size of the screen. If the recipe sheet touches
// the edge of the screen, use a slightly different layout.
final double appBarHeight = _getAppBarHeight(context);
final Size screenSize = MediaQuery.of(context).size;
final bool fullWidth = screenSize.width < _kRecipePageMaxWidth;
final bool isFavorite = _favoriteRecipes.contains(widget.recipe);
return Scaffold(
body: Stack(
children: <Widget>[
Positioned(
top: 0.0,
left: 0.0,
right: 0.0,
height: appBarHeight + _kFabHalfSize,
child: Hero(
tag: 'packages/$_kGalleryAssetsPackage/${widget.recipe!.imagePath}',
child: Image.asset(
widget.recipe!.imagePath!,
package: widget.recipe!.imagePackage,
fit: fullWidth ? BoxFit.fitWidth : BoxFit.cover,
),
),
),
CustomScrollView(
slivers: <Widget>[
SliverAppBar(
expandedHeight: appBarHeight - _kFabHalfSize,
backgroundColor: Colors.transparent,
actions: <Widget>[
PopupMenuButton<String>(
onSelected: (String item) { },
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
_buildMenuItem(Icons.share, 'Tweet recipe'),
_buildMenuItem(Icons.email, 'Email recipe'),
_buildMenuItem(Icons.message, 'Message recipe'),
_buildMenuItem(Icons.people, 'Share on Facebook'),
],
),
],
flexibleSpace: const FlexibleSpaceBar(
background: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment(0.0, -0.2),
colors: <Color>[Color(0x60000000), Color(0x00000000)],
),
),
),
),
),
SliverToBoxAdapter(
child: Stack(
children: <Widget>[
Container(
padding: const EdgeInsets.only(top: _kFabHalfSize),
width: fullWidth ? null : _kRecipePageMaxWidth,
child: RecipeSheet(recipe: widget.recipe),
),
Positioned(
right: 16.0,
child: FloatingActionButton(
backgroundColor: Colors.redAccent,
onPressed: _toggleFavorite,
child: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),
),
),
],
),
),
],
),
],
),
);
}
PopupMenuItem<String> _buildMenuItem(IconData icon, String label) {
return PopupMenuItem<String>(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 24.0),
child: Icon(icon, color: Colors.black54),
),
Text(label, style: menuItemStyle),
],
),
);
}
void _toggleFavorite() {
setState(() {
if (_favoriteRecipes.contains(widget.recipe)) {
_favoriteRecipes.remove(widget.recipe);
} else {
_favoriteRecipes.add(widget.recipe);
}
});
}
}
/// Displays the recipe's name and instructions.
class RecipeSheet extends StatelessWidget {
RecipeSheet({ super.key, this.recipe });
final TextStyle titleStyle = const PestoStyle(fontSize: 34.0);
final TextStyle descriptionStyle = const PestoStyle(fontSize: 15.0, color: Colors.black54, height: 24.0/15.0);
final TextStyle itemStyle = const PestoStyle(fontSize: 15.0, height: 24.0/15.0);
final TextStyle itemAmountStyle = PestoStyle(fontSize: 15.0, color: _kTheme.primaryColor, height: 24.0/15.0);
final TextStyle headingStyle = const PestoStyle(fontSize: 16.0, fontWeight: FontWeight.bold, height: 24.0/15.0);
final Recipe? recipe;
@override
Widget build(BuildContext context) {
return Material(
child: SafeArea(
top: false,
bottom: false,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 40.0),
child: Table(
columnWidths: const <int, TableColumnWidth>{
0: FixedColumnWidth(64.0),
},
children: <TableRow>[
TableRow(
children: <Widget>[
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Image.asset(
recipe!.ingredientsImagePath!,
package: recipe!.ingredientsImagePackage,
width: 32.0,
height: 32.0,
alignment: Alignment.centerLeft,
fit: BoxFit.scaleDown,
),
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.middle,
child: Text(recipe!.name!, style: titleStyle),
),
]
),
TableRow(
children: <Widget>[
const SizedBox(),
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 4.0),
child: Text(recipe!.description!, style: descriptionStyle),
),
]
),
TableRow(
children: <Widget>[
const SizedBox(),
Padding(
padding: const EdgeInsets.only(top: 24.0, bottom: 4.0),
child: Text('Ingredients', style: headingStyle),
),
]
),
...recipe!.ingredients!.map<TableRow>((RecipeIngredient ingredient) {
return _buildItemRow(ingredient.amount!, ingredient.description!);
}),
TableRow(
children: <Widget>[
const SizedBox(),
Padding(
padding: const EdgeInsets.only(top: 24.0, bottom: 4.0),
child: Text('Steps', style: headingStyle),
),
]
),
...recipe!.steps!.map<TableRow>((RecipeStep step) {
return _buildItemRow(step.duration ?? '', step.description!);
}),
],
),
),
),
);
}
TableRow _buildItemRow(String left, String right) {
return TableRow(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Text(left, style: itemAmountStyle),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Text(right, style: itemStyle),
),
],
);
}
}
class Recipe {
const Recipe({
this.name,
this.author,
this.description,
this.imagePath,
this.imagePackage,
this.ingredientsImagePath,
this.ingredientsImagePackage,
this.ingredients,
this.steps,
});
final String? name;
final String? author;
final String? description;
final String? imagePath;
final String? imagePackage;
final String? ingredientsImagePath;
final String? ingredientsImagePackage;
final List<RecipeIngredient>? ingredients;
final List<RecipeStep>? steps;
}
class RecipeIngredient {
const RecipeIngredient({this.amount, this.description});
final String? amount;
final String? description;
}
class RecipeStep {
const RecipeStep({this.duration, this.description});
final String? duration;
final String? description;
}
const List<Recipe> kPestoRecipes = <Recipe>[
Recipe(
name: 'Roasted Chicken',
author: 'Peter Carlsson',
ingredientsImagePath: 'food/icons/main.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: 'The perfect dish to welcome your family and friends with on a crisp autumn night. Pair with roasted veggies to truly impress them.',
imagePath: 'food/roasted_chicken.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '1 whole', description: 'Chicken'),
RecipeIngredient(amount: '1/2 cup', description: 'Butter'),
RecipeIngredient(amount: '1 tbsp', description: 'Onion powder'),
RecipeIngredient(amount: '1 tbsp', description: 'Freshly ground pepper'),
RecipeIngredient(amount: '1 tsp', description: 'Salt'),
],
steps: <RecipeStep>[
RecipeStep(duration: '1 min', description: 'Put in oven'),
RecipeStep(duration: '1hr 45 min', description: 'Cook'),
],
),
Recipe(
name: 'Chopped Beet Leaves',
author: 'Trevor Hansen',
ingredientsImagePath: 'food/icons/veggie.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: 'This vegetable has more to offer than just its root. Beet greens can be tossed into a salad to add some variety or sauteed on its own with some oil and garlic.',
imagePath: 'food/chopped_beet_leaves.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '3 cups', description: 'Beet greens'),
],
steps: <RecipeStep>[
RecipeStep(duration: '5 min', description: 'Chop'),
],
),
Recipe(
name: 'Pesto Pasta',
author: 'Ali Connors',
ingredientsImagePath: 'food/icons/main.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "With this pesto recipe, you can quickly whip up a meal to satisfy your savory needs. And if you're feeling festive, you can add bacon to taste.",
imagePath: 'food/pesto_pasta.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '1/4 cup ', description: 'Pasta'),
RecipeIngredient(amount: '2 cups', description: 'Fresh basil leaves'),
RecipeIngredient(amount: '1/2 cup', description: 'Parmesan cheese'),
RecipeIngredient(amount: '1/2 cup', description: 'Extra virgin olive oil'),
RecipeIngredient(amount: '1/3 cup', description: 'Pine nuts'),
RecipeIngredient(amount: '1/4 cup', description: 'Lemon juice'),
RecipeIngredient(amount: '3 cloves', description: 'Garlic'),
RecipeIngredient(amount: '1/4 tsp', description: 'Salt'),
RecipeIngredient(amount: '1/8 tsp', description: 'Pepper'),
RecipeIngredient(amount: '3 lbs', description: 'Bacon'),
],
steps: <RecipeStep>[
RecipeStep(duration: '15 min', description: 'Blend'),
],
),
Recipe(
name: 'Cherry Pie',
author: 'Sandra Adams',
ingredientsImagePath: 'food/icons/main.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "Sometimes when you're craving some cheer in your life you can jumpstart your day with some cherry pie. Dessert for breakfast is perfectly acceptable.",
imagePath: 'food/cherry_pie.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '1', description: 'Pie crust'),
RecipeIngredient(amount: '4 cups', description: 'Fresh or frozen cherries'),
RecipeIngredient(amount: '1 cup', description: 'Granulated sugar'),
RecipeIngredient(amount: '4 tbsp', description: 'Cornstarch'),
RecipeIngredient(amount: '1½ tbsp', description: 'Butter'),
],
steps: <RecipeStep>[
RecipeStep(duration: '15 min', description: 'Mix'),
RecipeStep(duration: '1hr 30 min', description: 'Bake'),
],
),
Recipe(
name: 'Spinach Salad',
author: 'Peter Carlsson',
ingredientsImagePath: 'food/icons/spicy.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "Everyone's favorite leafy green is back. Paired with fresh sliced onion, it's ready to tackle any dish, whether it be a salad or an egg scramble.",
imagePath: 'food/spinach_onion_salad.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '4 cups', description: 'Spinach'),
RecipeIngredient(amount: '1 cup', description: 'Sliced onion'),
],
steps: <RecipeStep>[
RecipeStep(duration: '5 min', description: 'Mix'),
],
),
Recipe(
name: 'Butternut Squash Soup',
author: 'Ali Connors',
ingredientsImagePath: 'food/icons/healthy.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: 'This creamy butternut squash soup will warm you on the chilliest of winter nights and bring a delightful pop of orange to the dinner table.',
imagePath: 'food/butternut_squash_soup.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '1', description: 'Butternut squash'),
RecipeIngredient(amount: '4 cups', description: 'Chicken stock'),
RecipeIngredient(amount: '2', description: 'Potatoes'),
RecipeIngredient(amount: '1', description: 'Onion'),
RecipeIngredient(amount: '1', description: 'Carrot'),
RecipeIngredient(amount: '1', description: 'Celery'),
RecipeIngredient(amount: '1 tsp', description: 'Salt'),
RecipeIngredient(amount: '1 tsp', description: 'Pepper'),
],
steps: <RecipeStep>[
RecipeStep(duration: '10 min', description: 'Prep vegetables'),
RecipeStep(duration: '5 min', description: 'Stir'),
RecipeStep(duration: '1 hr 10 min', description: 'Cook'),
],
),
Recipe(
name: 'Spanakopita',
author: 'Trevor Hansen',
ingredientsImagePath: 'food/icons/quick.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "You 'feta' believe this is a crowd-pleaser! Flaky phyllo pastry surrounds a delicious mixture of spinach and cheeses to create the perfect appetizer.",
imagePath: 'food/spanakopita.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '1 lb', description: 'Spinach'),
RecipeIngredient(amount: '½ cup', description: 'Feta cheese'),
RecipeIngredient(amount: '½ cup', description: 'Cottage cheese'),
RecipeIngredient(amount: '2', description: 'Eggs'),
RecipeIngredient(amount: '1', description: 'Onion'),
RecipeIngredient(amount: '½ lb', description: 'Phyllo dough'),
],
steps: <RecipeStep>[
RecipeStep(duration: '5 min', description: 'Sauté vegetables'),
RecipeStep(duration: '3 min', description: 'Stir vegetables and other filling ingredients'),
RecipeStep(duration: '10 min', description: 'Fill phyllo squares half-full with filling and fold.'),
RecipeStep(duration: '40 min', description: 'Bake'),
],
),
];
| flutter/dev/integration_tests/flutter_gallery/lib/demo/pesto_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/pesto_demo.dart",
"repo_id": "flutter",
"token_count": 11164
} | 525 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
const String _kStartTag = '// START ';
const String _kEndTag = '// END';
Map<String?, String>? _exampleCode;
Future<String?> getExampleCode(String? tag, AssetBundle bundle) async {
if (_exampleCode == null) {
await _parseExampleCode(bundle);
}
return _exampleCode![tag];
}
Future<void> _parseExampleCode(AssetBundle bundle) async {
final String code = await bundle.loadString('lib/gallery/example_code.dart');
_exampleCode = <String?, String>{};
final List<String> lines = code.split('\n');
List<String>? codeBlock;
String? codeTag;
for (final String line in lines) {
if (codeBlock == null) {
// Outside a block.
if (line.startsWith(_kStartTag)) {
// Starting a new code block.
codeBlock = <String>[];
codeTag = line.substring(_kStartTag.length).trim();
} else {
// Just skipping the line.
}
} else {
// Inside a block.
if (line.startsWith(_kEndTag)) {
// Add the block.
_exampleCode![codeTag] = codeBlock.join('\n');
codeBlock = null;
codeTag = null;
} else {
// Add to the current block
// trimRight() to remove any \r on Windows
// without removing any useful indentation
codeBlock.add(line.trimRight());
}
}
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart",
"repo_id": "flutter",
"token_count": 573
} | 526 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_gallery/demo/calculator_demo.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
if (binding is LiveTestWidgetsFlutterBinding) {
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
}
// We press the "1" and the "2" buttons and check that the display
// reads "12".
testWidgets('Flutter calculator app smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: CalculatorDemo()));
final Finder oneButton = find.widgetWithText(InkResponse, '1');
expect(oneButton, findsOneWidget);
final Finder twoButton = find.widgetWithText(InkResponse, '2');
expect(twoButton, findsOneWidget);
await tester.tap(oneButton);
await tester.pump();
await tester.tap(twoButton);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
final Finder display = find.widgetWithText(Expanded, '12');
expect(display, findsOneWidget);
});
}
| flutter/dev/integration_tests/flutter_gallery/test/calculator/smoke_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test/calculator/smoke_test.dart",
"repo_id": "flutter",
"token_count": 425
} | 527 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_gallery/gallery/app.dart' show GalleryApp;
import 'package:flutter_test/flutter_test.dart';
Future<String> mockUpdateUrlFetcher() {
// A real implementation would connect to the network to retrieve this value
return Future<String>.value('http://www.example.com/');
}
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
if (binding is LiveTestWidgetsFlutterBinding) {
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
}
// Regression test for https://github.com/flutter/flutter/pull/5168
testWidgets('update dialog', (WidgetTester tester) async {
await tester.pumpWidget(
const GalleryApp(
testMode: true,
updateUrlFetcher: mockUpdateUrlFetcher,
)
);
await tester.pump(); // see https://github.com/flutter/flutter/issues/1865
await tester.pump(); // triggers a frame
expect(find.text('UPDATE'), findsOneWidget);
await tester.tap(find.text('NO THANKS'));
await tester.pump();
await tester.tap(find.text('Studies'));
await tester.pump(); // Launch
await tester.pump(const Duration(seconds: 1)); // transition is complete
final Finder backButton = find.byTooltip('Back');
expect(backButton, findsOneWidget);
await tester.tap(backButton);
await tester.pump(); // Start the pop "back" operation.
await tester.pump(); // Complete the willPop() Future.
await tester.pump(const Duration(seconds: 1)); // transition is complete
//await tester.pumpUntilNoTransientCallbacks(const Duration(seconds: 1));
expect(find.text('UPDATE'), findsNothing);
});
}
| flutter/dev/integration_tests/flutter_gallery/test/update_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test/update_test.dart",
"repo_id": "flutter",
"token_count": 608
} | 528 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/scheduler.dart';
// See //dev/devicelab/bin/tasks/flutter_gallery__image_cache_memory.dart
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
// Once we provide an option for images to be resized to
// fit the container, we should see a significant drop in
// the amount of memory consumed by this benchmark.
Future<void> main() async {
const int numItems = 10;
runApp(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
key: const Key('ImageList'),
itemCount: numItems,
itemBuilder: (BuildContext context, int position) {
return SizedBox(
width: 200,
height: 200,
child: Center(
child: Image.asset(
'monochrome/red-square-1024x1024.png',
package: 'flutter_gallery_assets',
width: 100,
height: 100,
fit: BoxFit.contain,
key: Key('image_$position'),
),
),
);
},
),
));
await SchedulerBinding.instance.endOfFrame;
// We are waiting for the GPU to rasterize a frame here. This makes this
// flaky, we can rely on a more deterministic source such as
// PlatformDispatcher.onReportTimings once
// https://github.com/flutter/flutter/issues/26154 is addressed.
await Future<void>.delayed(const Duration(milliseconds: 50));
debugPrint('==== MEMORY BENCHMARK ==== READY ====');
final WidgetController controller =
LiveWidgetController(WidgetsBinding.instance);
debugPrint('Scrolling...');
final Finder list = find.byKey(const Key('ImageList'));
final Finder lastItem = find.byKey(const Key('image_${numItems - 1}'));
do {
await controller.drag(list, const Offset(0.0, -30.0));
await Future<void>.delayed(const Duration(milliseconds: 20));
} while (!lastItem.tryEvaluate());
debugPrint('==== MEMORY BENCHMARK ==== DONE ====');
}
| flutter/dev/integration_tests/flutter_gallery/test_memory/image_cache_memory.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test_memory/image_cache_memory.dart",
"repo_id": "flutter",
"token_count": 797
} | 529 |
platform :ios, '12.0'
flutter_application_path = 'flutterapp/'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'ios_add2app' do
install_all_flutter_pods(flutter_application_path)
pod 'EarlGreyApp'
end
target 'ios_add2appTests' do
install_flutter_engine_pod(flutter_application_path)
pod 'EarlGreyTest'
end
post_install do |installer|
flutter_post_install(installer)
end
| flutter/dev/integration_tests/ios_add2app_life_cycle/Podfile/0 | {
"file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/Podfile",
"repo_id": "flutter",
"token_count": 160
} | 530 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// HostingController.swift
// watch Extension
//
// Created by Georg Wechslberger on 08.04.20.
//
import Foundation
import SwiftUI
import WatchKit
class HostingController: WKHostingController<ContentView> {
override var body: ContentView {
return ContentView()
}
}
| flutter/dev/integration_tests/ios_app_with_extensions/ios/watch Extension/HostingController.swift/0 | {
"file_path": "flutter/dev/integration_tests/ios_app_with_extensions/ios/watch Extension/HostingController.swift",
"repo_id": "flutter",
"token_count": 138
} | 531 |
// Copyright 2014 The Flutter 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 "NativeViewController.h"
@interface NativeViewController ()
@end
@implementation NativeViewController {
int _counter;
UILabel* _incrementLabel;
}
- (instancetype)initWithDelegate:(id<NativeViewControllerDelegate>)delegate {
self = [super initWithNibName:nil bundle:nil];
if (self) {
self.delegate = delegate;
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
return [self initWithDelegate:nil];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
return [self initWithDelegate:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Native iOS View";
self.view.backgroundColor = UIColor.lightGrayColor;
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"Back"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
_incrementLabel = [self addIncrementLabel];
UIStackView* footer = [self addFooter];
_incrementLabel.translatesAutoresizingMaskIntoConstraints = false;
footer.translatesAutoresizingMaskIntoConstraints = false;
UILayoutGuide* marginsGuide = self.view.layoutMarginsGuide;
NSMutableArray* array = [[NSMutableArray alloc] init];
[array addObject:[_incrementLabel.centerXAnchor
constraintEqualToAnchor:self.view.centerXAnchor]];
[array addObject:[_incrementLabel.centerYAnchor
constraintEqualToAnchor:self.view.centerYAnchor]];
[array addObject:[footer.centerXAnchor
constraintEqualToAnchor:self.view.centerXAnchor]];
[array addObject:[footer.widthAnchor
constraintEqualToAnchor:marginsGuide.widthAnchor]];
[array addObject:[footer.bottomAnchor
constraintEqualToAnchor:marginsGuide.bottomAnchor]];
[NSLayoutConstraint activateConstraints:array];
[self updateIncrementLabel];
}
/// Adds a label to the view that will contain the counter text.
///
/// - Returns: The new label.
-(UILabel*) addIncrementLabel {
UILabel* incrementLabel = [[UILabel alloc] init];
incrementLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
incrementLabel.textColor = UIColor.blackColor;
incrementLabel.accessibilityIdentifier = @"counter_on_iOS";
[self.view addSubview:incrementLabel];
return incrementLabel;
}
/// Adds a horizontal stack to the view, anchored to the bottom.
///
/// - Returns: The new stack.
-(UIStackView*) addFooter {
UILabel* mainLabel = [self createMainLabel];
UIButton* incrementButton = [self createIncrementButton];
UIStackView* stackView = [[UIStackView alloc] initWithFrame:self.view.frame];
[stackView addArrangedSubview:mainLabel];
[stackView addArrangedSubview:incrementButton];
stackView.axis = UILayoutConstraintAxisHorizontal;
stackView.alignment = UIStackViewAlignmentBottom;
[self.view addSubview:stackView];
return stackView;
}
/// Creates a label identifying this view. Does not add it to the view.
///
/// - Returns: The new label.
-(UILabel*) createMainLabel {
UILabel* mainLabel = [[UILabel alloc] init];
mainLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleTitle1];
mainLabel.textColor = UIColor.blackColor;
mainLabel.text = @"Native";
return mainLabel;
}
/// Creates a button that will increment a counter. Does not add it to the view.
///
/// - Returns: The new button.
-(UIButton*) createIncrementButton {
UIButton *incrementButton = [UIButton buttonWithType:UIButtonTypeSystem];
incrementButton.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleTitle2];
[incrementButton setTitle:@"Add" forState:UIControlStateNormal];
incrementButton.accessibilityLabel = @"Increment via iOS";
incrementButton.layer.cornerRadius = 15.0;
[incrementButton addTarget:self
action:@selector(handleIncrement:)
forControlEvents:UIControlEventTouchUpInside];
return incrementButton;
}
// MARK: - Actions
/// Action triggered from tapping on the increment button. Triggers a corresponding event in the
/// delegate if one is available, otherwise increments our internal counter.
-(void) handleIncrement:(UIButton*)sender {
if (self.delegate) {
[self.delegate didTapIncrementButton];
} else {
[self didReceiveIncrement];
}
}
/// Updates the increment label text to match the increment counter.
-(void) updateIncrementLabel {
_incrementLabel.text = [NSString
stringWithFormat:@"%@ tapped %d %@.",
self.delegate == nil ? @"Button" : @"Flutter button",
_counter, _counter == 1 ? @"time" : @"times"];
}
/// Increments our internal counter and updates the view.
-(void) didReceiveIncrement {
_counter += 1;
[self updateIncrementLabel];
}
@end
| flutter/dev/integration_tests/ios_host_app/Host/NativeViewController.m/0 | {
"file_path": "flutter/dev/integration_tests/ios_host_app/Host/NativeViewController.m",
"repo_id": "flutter",
"token_count": 1958
} | 532 |
// Copyright 2014 The Flutter 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 UIKit
import Flutter
import FlutterPluginRegistrant
class ViewController: UIViewController {
var flutterEngine : FlutterEngine?;
// Boiler-plate add-to-app demo. Not integration tested anywhere.
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type:UIButton.ButtonType.custom)
button.addTarget(self, action: #selector(handleButtonAction), for: .touchUpInside)
button.setTitle("Press me", for: UIControl.State.normal)
button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
button.backgroundColor = UIColor.blue
self.view.addSubview(button)
self.flutterEngine = FlutterEngine(name: "io.flutter", project: nil);
}
@objc func handleButtonAction() {
if let flutterEngine = flutterEngine as? FlutterEngine {
GeneratedPluginRegistrant.register(with: flutterEngine);
let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil);
self.present(flutterViewController, animated: false, completion: nil)
}
}
}
| flutter/dev/integration_tests/ios_host_app_swift/Host/ViewController.swift/0 | {
"file_path": "flutter/dev/integration_tests/ios_host_app_swift/Host/ViewController.swift",
"repo_id": "flutter",
"token_count": 399
} | 533 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import '../../gallery_localizations.dart';
// BEGIN cupertinoSegmentedControlDemo
class CupertinoSegmentedControlDemo extends StatefulWidget {
const CupertinoSegmentedControlDemo({super.key});
@override
State<CupertinoSegmentedControlDemo> createState() =>
_CupertinoSegmentedControlDemoState();
}
class _CupertinoSegmentedControlDemoState
extends State<CupertinoSegmentedControlDemo> with RestorationMixin {
RestorableInt currentSegment = RestorableInt(0);
@override
String get restorationId => 'cupertino_segmented_control';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(currentSegment, 'current_segment');
}
void onValueChanged(int? newValue) {
setState(() {
currentSegment.value = newValue!;
});
}
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
const double segmentedControlMaxWidth = 500.0;
final Map<int, Widget> children = <int, Widget>{
0: Text(localizations.colorsIndigo),
1: Text(localizations.colorsTeal),
2: Text(localizations.colorsCyan),
};
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle: Text(
localizations.demoCupertinoSegmentedControlTitle,
),
),
child: DefaultTextStyle(
style: CupertinoTheme.of(context)
.textTheme
.textStyle
.copyWith(fontSize: 13),
child: SafeArea(
child: ListView(
children: <Widget>[
const SizedBox(height: 16),
SizedBox(
width: segmentedControlMaxWidth,
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: onValueChanged,
groupValue: currentSegment.value,
),
),
SizedBox(
width: segmentedControlMaxWidth,
child: Padding(
padding: const EdgeInsets.all(16),
child: CupertinoSlidingSegmentedControl<int>(
children: children,
onValueChanged: onValueChanged,
groupValue: currentSegment.value,
),
),
),
Container(
padding: const EdgeInsets.all(16),
height: 300,
alignment: Alignment.center,
child: children[currentSegment.value],
),
],
),
),
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_segmented_control_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_segmented_control_demo.dart",
"repo_id": "flutter",
"token_count": 1313
} | 534 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../gallery_localizations.dart';
import 'material_demo_types.dart';
class DividerDemo extends StatelessWidget {
const DividerDemo({super.key, required this.type});
final DividerDemoType type;
String _title(BuildContext context) {
switch (type) {
case DividerDemoType.horizontal:
return GalleryLocalizations.of(context)!.demoDividerTitle;
case DividerDemoType.vertical:
return GalleryLocalizations.of(context)!.demoVerticalDividerTitle;
}
}
@override
Widget build(BuildContext context) {
late Widget dividers;
switch (type) {
case DividerDemoType.horizontal:
dividers = _HorizontalDividerDemo();
case DividerDemoType.vertical:
dividers = _VerticalDividerDemo();
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(
_title(context),
),
),
body: dividers,
);
}
}
// BEGIN dividerDemo
class _HorizontalDividerDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10),
child: Column(
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.deepPurpleAccent,
),
),
),
const Divider(
color: Colors.grey,
height: 20,
thickness: 1,
indent: 20,
endIndent: 0,
),
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.deepOrangeAccent,
),
),
),
],
),
);
}
}
// END
// BEGIN verticalDividerDemo
class _VerticalDividerDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10),
child: Row(
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.deepPurpleAccent,
),
),
),
const VerticalDivider(
color: Colors.grey,
thickness: 1,
indent: 20,
endIndent: 0,
width: 20,
),
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.deepOrangeAccent,
),
),
),
],
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/material/divider_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/divider_demo.dart",
"repo_id": "flutter",
"token_count": 1465
} | 535 |
// Copyright 2014 The Flutter 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:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart' as intl;
import 'gallery_localizations_en.dart';
/// Callers can lookup localized strings with an instance of GalleryLocalizations
/// returned by `GalleryLocalizations.of(context)`.
///
/// Applications need to include `GalleryLocalizations.delegate()` in their app's
/// `localizationDelegates` list, and the locales they support in the app's
/// `supportedLocales` list. For example:
///
/// ```dart
/// import 'gen_l10n/gallery_localizations.dart';
///
/// return MaterialApp(
/// localizationsDelegates: GalleryLocalizations.localizationsDelegates,
/// supportedLocales: GalleryLocalizations.supportedLocales,
/// home: MyApplicationHome(),
/// );
/// ```
///
/// ## Update pubspec.yaml
///
/// Please make sure to update your pubspec.yaml to include the following
/// packages:
///
/// ```yaml
/// dependencies:
/// # Internationalization support.
/// flutter_localizations:
/// sdk: flutter
/// intl: any # Use the pinned version from flutter_localizations
///
/// # Rest of dependencies
/// ```
///
/// ## iOS Applications
///
/// iOS applications define key application metadata, including supported
/// locales, in an Info.plist file that is built into the application bundle.
/// To configure the locales supported by your app, you’ll need to edit this
/// file.
///
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
/// Then, in the Project Navigator, open the Info.plist file under the Runner
/// project’s Runner folder.
///
/// Next, select the Information Property List item, select Add Item from the
/// Editor menu, then select Localizations from the pop-up menu.
///
/// Select and expand the newly-created Localizations item then, for each
/// locale your application supports, add a new item and select the locale
/// you wish to add from the pop-up menu in the Value field. This list should
/// be consistent with the languages listed in the GalleryLocalizations.supportedLocales
/// property.
abstract class GalleryLocalizations {
GalleryLocalizations(String locale) : localeName = intl.Intl.canonicalizedLocale(locale);
final String localeName;
static GalleryLocalizations? of(BuildContext context) {
return Localizations.of<GalleryLocalizations>(context, GalleryLocalizations);
}
static const LocalizationsDelegate<GalleryLocalizations> delegate = _GalleryLocalizationsDelegate();
/// A list of this localizations delegate along with the default localizations
/// delegates.
///
/// Returns a list of localizations delegates containing this delegate along with
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
/// and GlobalWidgetsLocalizations.delegate.
///
/// Additional delegates can be added by appending to this list in
/// MaterialApp. This list does not have to be used at all if a custom list
/// of delegates is preferred or required.
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
/// A list of this localizations delegate's supported locales.
static const List<Locale> supportedLocales = <Locale>[
Locale('en'),
Locale('en', 'IS')
];
/// Represents a link to a GitHub repository.
///
/// In en, this message translates to:
/// **'{repoName} GitHub repository'**
String githubRepo(Object repoName);
/// A description about how to view the source code for this app.
///
/// In en, this message translates to:
/// **'To see the source code for this app, please visit the {repoLink}.'**
String aboutDialogDescription(Object repoLink);
/// Deselect a (selectable) item
///
/// In en, this message translates to:
/// **'Deselect'**
String get deselect;
/// Indicates the status of a (selectable) item not being selected
///
/// In en, this message translates to:
/// **'Not selected'**
String get notSelected;
/// Select a (selectable) item
///
/// In en, this message translates to:
/// **'Select'**
String get select;
/// Indicates the associated piece of UI is selectable by long pressing it
///
/// In en, this message translates to:
/// **'Selectable (long press)'**
String get selectable;
/// Indicates status of a (selectable) item being selected
///
/// In en, this message translates to:
/// **'Selected'**
String get selected;
/// Sign in label to sign into website.
///
/// In en, this message translates to:
/// **'SIGN IN'**
String get signIn;
/// Password was updated on a different device and the user is required to sign in again
///
/// In en, this message translates to:
/// **'Your password was updated on your other device. Please sign in again.'**
String get bannerDemoText;
/// Show the Banner to the user again.
///
/// In en, this message translates to:
/// **'Reset the banner'**
String get bannerDemoResetText;
/// When the user clicks this button the Banner will toggle multiple actions or a single action
///
/// In en, this message translates to:
/// **'Multiple actions'**
String get bannerDemoMultipleText;
/// If user clicks this button the leading icon in the Banner will disappear
///
/// In en, this message translates to:
/// **'Leading Icon'**
String get bannerDemoLeadingText;
/// When text is pressed the banner widget will be removed from the screen.
///
/// In en, this message translates to:
/// **'DISMISS'**
String get dismiss;
/// Semantic label for back button to exit a study and return to the gallery home page.
///
/// In en, this message translates to:
/// **'Back to Gallery'**
String get backToGallery;
/// Click to see more about the content in the cards demo.
///
/// In en, this message translates to:
/// **'Explore'**
String get cardsDemoExplore;
/// Semantics label for Explore. Label tells user to explore the destinationName to the user. Example Explore Tamil
///
/// In en, this message translates to:
/// **'Explore {destinationName}'**
String cardsDemoExploreSemantics(Object destinationName);
/// Semantics label for Share. Label tells user to share the destinationName to the user. Example Share Tamil
///
/// In en, this message translates to:
/// **'Share {destinationName}'**
String cardsDemoShareSemantics(Object destinationName);
/// The user can tap this button
///
/// In en, this message translates to:
/// **'Tappable'**
String get cardsDemoTappable;
/// The top 10 cities that you can visit in Tamil Nadu
///
/// In en, this message translates to:
/// **'Top 10 Cities to Visit in Tamil Nadu'**
String get cardsDemoTravelDestinationTitle1;
/// Number 10
///
/// In en, this message translates to:
/// **'Number 10'**
String get cardsDemoTravelDestinationDescription1;
/// Thanjavur the city
///
/// In en, this message translates to:
/// **'Thanjavur'**
String get cardsDemoTravelDestinationCity1;
/// Thanjavur, Tamil Nadu is a location
///
/// In en, this message translates to:
/// **'Thanjavur, Tamil Nadu'**
String get cardsDemoTravelDestinationLocation1;
/// Artist that are from Southern India
///
/// In en, this message translates to:
/// **'Artisans of Southern India'**
String get cardsDemoTravelDestinationTitle2;
/// Silk Spinners
///
/// In en, this message translates to:
/// **'Silk Spinners'**
String get cardsDemoTravelDestinationDescription2;
/// Chettinad the city
///
/// In en, this message translates to:
/// **'Chettinad'**
String get cardsDemoTravelDestinationCity2;
/// Sivaganga, Tamil Nadu is a location
///
/// In en, this message translates to:
/// **'Sivaganga, Tamil Nadu'**
String get cardsDemoTravelDestinationLocation2;
/// Brihadisvara Temple
///
/// In en, this message translates to:
/// **'Brihadisvara Temple'**
String get cardsDemoTravelDestinationTitle3;
/// Temples
///
/// In en, this message translates to:
/// **'Temples'**
String get cardsDemoTravelDestinationDescription3;
/// Header title on home screen for Gallery section.
///
/// In en, this message translates to:
/// **'Gallery'**
String get homeHeaderGallery;
/// Header title on home screen for Categories section.
///
/// In en, this message translates to:
/// **'Categories'**
String get homeHeaderCategories;
/// Study description for Shrine.
///
/// In en, this message translates to:
/// **'A fashionable retail app'**
String get shrineDescription;
/// Study description for Fortnightly.
///
/// In en, this message translates to:
/// **'A content-focused news app'**
String get fortnightlyDescription;
/// Study description for Rally.
///
/// In en, this message translates to:
/// **'A personal finance app'**
String get rallyDescription;
/// Study description for Reply.
///
/// In en, this message translates to:
/// **'An efficient, focused email app'**
String get replyDescription;
/// Name for account made up by user.
///
/// In en, this message translates to:
/// **'Checking'**
String get rallyAccountDataChecking;
/// Name for account made up by user.
///
/// In en, this message translates to:
/// **'Home Savings'**
String get rallyAccountDataHomeSavings;
/// Name for account made up by user.
///
/// In en, this message translates to:
/// **'Car Savings'**
String get rallyAccountDataCarSavings;
/// Name for account made up by user.
///
/// In en, this message translates to:
/// **'Vacation'**
String get rallyAccountDataVacation;
/// Title for account statistics. Below a percentage such as 0.10% will be displayed.
///
/// In en, this message translates to:
/// **'Annual Percentage Yield'**
String get rallyAccountDetailDataAnnualPercentageYield;
/// Title for account statistics. Below a dollar amount such as $100 will be displayed.
///
/// In en, this message translates to:
/// **'Interest Rate'**
String get rallyAccountDetailDataInterestRate;
/// Title for account statistics. Below a dollar amount such as $100 will be displayed.
///
/// In en, this message translates to:
/// **'Interest YTD'**
String get rallyAccountDetailDataInterestYtd;
/// Title for account statistics. Below a dollar amount such as $100 will be displayed.
///
/// In en, this message translates to:
/// **'Interest Paid Last Year'**
String get rallyAccountDetailDataInterestPaidLastYear;
/// Title for an account detail. Below a date for when the next account statement is released.
///
/// In en, this message translates to:
/// **'Next Statement'**
String get rallyAccountDetailDataNextStatement;
/// Title for an account detail. Below the name of the account owner will be displayed.
///
/// In en, this message translates to:
/// **'Account Owner'**
String get rallyAccountDetailDataAccountOwner;
/// Title for column where it displays the total dollar amount that the user has in bills.
///
/// In en, this message translates to:
/// **'Total Amount'**
String get rallyBillDetailTotalAmount;
/// Title for column where it displays the amount that the user has paid.
///
/// In en, this message translates to:
/// **'Amount Paid'**
String get rallyBillDetailAmountPaid;
/// Title for column where it displays the amount that the user has due.
///
/// In en, this message translates to:
/// **'Amount Due'**
String get rallyBillDetailAmountDue;
/// Category for budget, to sort expenses / bills in.
///
/// In en, this message translates to:
/// **'Coffee Shops'**
String get rallyBudgetCategoryCoffeeShops;
/// Category for budget, to sort expenses / bills in.
///
/// In en, this message translates to:
/// **'Groceries'**
String get rallyBudgetCategoryGroceries;
/// Category for budget, to sort expenses / bills in.
///
/// In en, this message translates to:
/// **'Restaurants'**
String get rallyBudgetCategoryRestaurants;
/// Category for budget, to sort expenses / bills in.
///
/// In en, this message translates to:
/// **'Clothing'**
String get rallyBudgetCategoryClothing;
/// Title for column where it displays the total dollar cap that the user has for its budget.
///
/// In en, this message translates to:
/// **'Total Cap'**
String get rallyBudgetDetailTotalCap;
/// Title for column where it displays the dollar amount that the user has used in its budget.
///
/// In en, this message translates to:
/// **'Amount Used'**
String get rallyBudgetDetailAmountUsed;
/// Title for column where it displays the dollar amount that the user has left in its budget.
///
/// In en, this message translates to:
/// **'Amount Left'**
String get rallyBudgetDetailAmountLeft;
/// Link to go to the page 'Manage Accounts.
///
/// In en, this message translates to:
/// **'Manage Accounts'**
String get rallySettingsManageAccounts;
/// Link to go to the page 'Tax Documents'.
///
/// In en, this message translates to:
/// **'Tax Documents'**
String get rallySettingsTaxDocuments;
/// Link to go to the page 'Passcode and Touch ID'.
///
/// In en, this message translates to:
/// **'Passcode and Touch ID'**
String get rallySettingsPasscodeAndTouchId;
/// Link to go to the page 'Notifications'.
///
/// In en, this message translates to:
/// **'Notifications'**
String get rallySettingsNotifications;
/// Link to go to the page 'Personal Information'.
///
/// In en, this message translates to:
/// **'Personal Information'**
String get rallySettingsPersonalInformation;
/// Link to go to the page 'Paperless Settings'.
///
/// In en, this message translates to:
/// **'Paperless Settings'**
String get rallySettingsPaperlessSettings;
/// Link to go to the page 'Find ATMs'.
///
/// In en, this message translates to:
/// **'Find ATMs'**
String get rallySettingsFindAtms;
/// Link to go to the page 'Help'.
///
/// In en, this message translates to:
/// **'Help'**
String get rallySettingsHelp;
/// Link to go to the page 'Sign out'.
///
/// In en, this message translates to:
/// **'Sign out'**
String get rallySettingsSignOut;
/// Title for 'total account value' overview page, a dollar value is displayed next to it.
///
/// In en, this message translates to:
/// **'Total'**
String get rallyAccountTotal;
/// Title for 'bills due' page, a dollar value is displayed next to it.
///
/// In en, this message translates to:
/// **'Due'**
String get rallyBillsDue;
/// Title for 'budget left' page, a dollar value is displayed next to it.
///
/// In en, this message translates to:
/// **'Left'**
String get rallyBudgetLeft;
/// Link text for accounts page.
///
/// In en, this message translates to:
/// **'Accounts'**
String get rallyAccounts;
/// Link text for bills page.
///
/// In en, this message translates to:
/// **'Bills'**
String get rallyBills;
/// Link text for budgets page.
///
/// In en, this message translates to:
/// **'Budgets'**
String get rallyBudgets;
/// Title for alerts part of overview page.
///
/// In en, this message translates to:
/// **'Alerts'**
String get rallyAlerts;
/// Link text for button to see all data for category.
///
/// In en, this message translates to:
/// **'SEE ALL'**
String get rallySeeAll;
/// Displayed as 'dollar amount left', for example $46.70 LEFT, for a budget category.
///
/// In en, this message translates to:
/// **' LEFT'**
String get rallyFinanceLeft;
/// The navigation link to the overview page.
///
/// In en, this message translates to:
/// **'OVERVIEW'**
String get rallyTitleOverview;
/// The navigation link to the accounts page.
///
/// In en, this message translates to:
/// **'ACCOUNTS'**
String get rallyTitleAccounts;
/// The navigation link to the bills page.
///
/// In en, this message translates to:
/// **'BILLS'**
String get rallyTitleBills;
/// The navigation link to the budgets page.
///
/// In en, this message translates to:
/// **'BUDGETS'**
String get rallyTitleBudgets;
/// The navigation link to the settings page.
///
/// In en, this message translates to:
/// **'SETTINGS'**
String get rallyTitleSettings;
/// Title for login page for the Rally app (Rally does not need to be translated as it is a product name).
///
/// In en, this message translates to:
/// **'Login to Rally'**
String get rallyLoginLoginToRally;
/// Prompt for signing up for an account.
///
/// In en, this message translates to:
/// **'Don\'t have an account?'**
String get rallyLoginNoAccount;
/// Button text to sign up for an account.
///
/// In en, this message translates to:
/// **'SIGN UP'**
String get rallyLoginSignUp;
/// The username field in an login form.
///
/// In en, this message translates to:
/// **'Username'**
String get rallyLoginUsername;
/// The password field in an login form.
///
/// In en, this message translates to:
/// **'Password'**
String get rallyLoginPassword;
/// The label text to login.
///
/// In en, this message translates to:
/// **'Login'**
String get rallyLoginLabelLogin;
/// Text if the user wants to stay logged in.
///
/// In en, this message translates to:
/// **'Remember Me'**
String get rallyLoginRememberMe;
/// Text for login button.
///
/// In en, this message translates to:
/// **'LOGIN'**
String get rallyLoginButtonLogin;
/// Alert message shown when for example, user has used more than 90% of their shopping budget.
///
/// In en, this message translates to:
/// **'Heads up, you\'ve used up {percent} of your Shopping budget for this month.'**
String rallyAlertsMessageHeadsUpShopping(Object percent);
/// Alert message shown when for example, user has spent $120 on Restaurants this week.
///
/// In en, this message translates to:
/// **'You\'ve spent {amount} on Restaurants this week.'**
String rallyAlertsMessageSpentOnRestaurants(Object amount);
/// Alert message shown when for example, the user has spent $24 in ATM fees this month.
///
/// In en, this message translates to:
/// **'You\'ve spent {amount} in ATM fees this month'**
String rallyAlertsMessageATMFees(Object amount);
/// Alert message shown when for example, the checking account is 1% higher than last month.
///
/// In en, this message translates to:
/// **'Good work! Your checking account is {percent} higher than last month.'**
String rallyAlertsMessageCheckingAccount(Object percent);
/// Alert message shown when you have unassigned transactions.
///
/// In en, this message translates to:
/// **'{count, plural, =1{Increase your potential tax deduction! Assign categories to 1 unassigned transaction.}other{Increase your potential tax deduction! Assign categories to {count} unassigned transactions.}}'**
String rallyAlertsMessageUnassignedTransactions(num count);
/// Semantics label for button to see all accounts. Accounts refer to bank account here.
///
/// In en, this message translates to:
/// **'See all accounts'**
String get rallySeeAllAccounts;
/// Semantics label for button to see all bills.
///
/// In en, this message translates to:
/// **'See all bills'**
String get rallySeeAllBills;
/// Semantics label for button to see all budgets.
///
/// In en, this message translates to:
/// **'See all budgets'**
String get rallySeeAllBudgets;
/// Semantics label for row with bank account name (for example checking) and its bank account number (for example 123), with how much money is deposited in it (for example $12).
///
/// In en, this message translates to:
/// **'{accountName} account {accountNumber} with {amount}.'**
String rallyAccountAmount(Object accountName, Object accountNumber, Object amount);
/// Semantics label for row with a bill (example name is rent), when the bill is due (1/12/2019 for example) and for how much money ($12).
///
/// In en, this message translates to:
/// **'{billName} bill due {date} for {amount}.'**
String rallyBillAmount(Object billName, Object date, Object amount);
/// Semantics label for row with a budget (housing budget for example), with how much is used of the budget (for example $5), the total budget (for example $100) and the amount left in the budget (for example $95).
///
/// In en, this message translates to:
/// **'{budgetName} budget with {amountUsed} used of {amountTotal}, {amountLeft} left'**
String rallyBudgetAmount(Object budgetName, Object amountUsed, Object amountTotal, Object amountLeft);
/// Study description for Crane.
///
/// In en, this message translates to:
/// **'A personalized travel app'**
String get craneDescription;
/// Category title on home screen for styles & other demos (for context, the styles demos consist of a color demo and a typography demo).
///
/// In en, this message translates to:
/// **'STYLES & OTHER'**
String get homeCategoryReference;
/// Error message when opening the URL for a demo.
///
/// In en, this message translates to:
/// **'Couldn\'t display URL:'**
String get demoInvalidURL;
/// Tooltip for options button in a demo.
///
/// In en, this message translates to:
/// **'Options'**
String get demoOptionsTooltip;
/// Tooltip for info button in a demo.
///
/// In en, this message translates to:
/// **'Info'**
String get demoInfoTooltip;
/// Tooltip for demo code button in a demo.
///
/// In en, this message translates to:
/// **'Demo Code'**
String get demoCodeTooltip;
/// Tooltip for API documentation button in a demo.
///
/// In en, this message translates to:
/// **'API Documentation'**
String get demoDocumentationTooltip;
/// Tooltip for Full Screen button in a demo.
///
/// In en, this message translates to:
/// **'Full Screen'**
String get demoFullscreenTooltip;
/// Caption for a button to copy all text.
///
/// In en, this message translates to:
/// **'COPY ALL'**
String get demoCodeViewerCopyAll;
/// A message displayed to the user after clicking the COPY ALL button, if the text is successfully copied to the clipboard.
///
/// In en, this message translates to:
/// **'Copied to clipboard.'**
String get demoCodeViewerCopiedToClipboardMessage;
/// A message displayed to the user after clicking the COPY ALL button, if the text CANNOT be copied to the clipboard.
///
/// In en, this message translates to:
/// **'Failed to copy to clipboard: {error}'**
String demoCodeViewerFailedToCopyToClipboardMessage(Object error);
/// Title for an alert that explains what the options button does.
///
/// In en, this message translates to:
/// **'View options'**
String get demoOptionsFeatureTitle;
/// Description for an alert that explains what the options button does.
///
/// In en, this message translates to:
/// **'Tap here to view available options for this demo.'**
String get demoOptionsFeatureDescription;
/// Title for the settings screen.
///
/// In en, this message translates to:
/// **'Settings'**
String get settingsTitle;
/// Accessibility label for the settings button when settings are not showing.
///
/// In en, this message translates to:
/// **'Settings'**
String get settingsButtonLabel;
/// Accessibility label for the settings button when settings are showing.
///
/// In en, this message translates to:
/// **'Close settings'**
String get settingsButtonCloseLabel;
/// Option label to indicate the system default will be used.
///
/// In en, this message translates to:
/// **'System'**
String get settingsSystemDefault;
/// Title for text scaling setting.
///
/// In en, this message translates to:
/// **'Text scaling'**
String get settingsTextScaling;
/// Option label for small text scale setting.
///
/// In en, this message translates to:
/// **'Small'**
String get settingsTextScalingSmall;
/// Option label for normal text scale setting.
///
/// In en, this message translates to:
/// **'Normal'**
String get settingsTextScalingNormal;
/// Option label for large text scale setting.
///
/// In en, this message translates to:
/// **'Large'**
String get settingsTextScalingLarge;
/// Option label for huge text scale setting.
///
/// In en, this message translates to:
/// **'Huge'**
String get settingsTextScalingHuge;
/// Title for text direction setting.
///
/// In en, this message translates to:
/// **'Text direction'**
String get settingsTextDirection;
/// Option label for locale-based text direction setting.
///
/// In en, this message translates to:
/// **'Based on locale'**
String get settingsTextDirectionLocaleBased;
/// Option label for left-to-right text direction setting.
///
/// In en, this message translates to:
/// **'LTR'**
String get settingsTextDirectionLTR;
/// Option label for right-to-left text direction setting.
///
/// In en, this message translates to:
/// **'RTL'**
String get settingsTextDirectionRTL;
/// Title for locale setting.
///
/// In en, this message translates to:
/// **'Locale'**
String get settingsLocale;
/// Title for platform mechanics (iOS, Android, macOS, etc.) setting.
///
/// In en, this message translates to:
/// **'Platform mechanics'**
String get settingsPlatformMechanics;
/// Title for the theme setting.
///
/// In en, this message translates to:
/// **'Theme'**
String get settingsTheme;
/// Title for the dark theme setting.
///
/// In en, this message translates to:
/// **'Dark'**
String get settingsDarkTheme;
/// Title for the light theme setting.
///
/// In en, this message translates to:
/// **'Light'**
String get settingsLightTheme;
/// Title for slow motion setting.
///
/// In en, this message translates to:
/// **'Slow motion'**
String get settingsSlowMotion;
/// Title for information button.
///
/// In en, this message translates to:
/// **'About Flutter Gallery'**
String get settingsAbout;
/// Title for feedback button.
///
/// In en, this message translates to:
/// **'Send feedback'**
String get settingsFeedback;
/// Title for attribution (TOASTER is a proper name and should remain in English).
///
/// In en, this message translates to:
/// **'Designed by TOASTER in London'**
String get settingsAttribution;
/// Title for the material App bar component demo.
///
/// In en, this message translates to:
/// **'App bar'**
String get demoAppBarTitle;
/// Subtitle for the material App bar component demo.
///
/// In en, this message translates to:
/// **'Displays information and actions relating to the current screen'**
String get demoAppBarSubtitle;
/// Description for the material App bar component demo.
///
/// In en, this message translates to:
/// **'The App bar provides content and actions related to the current screen. It\'s used for branding, screen titles, navigation, and actions'**
String get demoAppBarDescription;
/// Title for the material bottom app bar component demo.
///
/// In en, this message translates to:
/// **'Bottom app bar'**
String get demoBottomAppBarTitle;
/// Subtitle for the material bottom app bar component demo.
///
/// In en, this message translates to:
/// **'Displays navigation and actions at the bottom'**
String get demoBottomAppBarSubtitle;
/// Description for the material bottom app bar component demo.
///
/// In en, this message translates to:
/// **'Bottom app bars provide access to a bottom navigation drawer and up to four actions, including the floating action button.'**
String get demoBottomAppBarDescription;
/// A toggle for whether to have a notch (or cutout) in the bottom app bar demo.
///
/// In en, this message translates to:
/// **'Notch'**
String get bottomAppBarNotch;
/// A setting for the position of the floating action button in the bottom app bar demo.
///
/// In en, this message translates to:
/// **'Floating Action Button Position'**
String get bottomAppBarPosition;
/// A setting for the position of the floating action button in the bottom app bar that docks the button in the bar and aligns it at the end.
///
/// In en, this message translates to:
/// **'Docked - End'**
String get bottomAppBarPositionDockedEnd;
/// A setting for the position of the floating action button in the bottom app bar that docks the button in the bar and aligns it in the center.
///
/// In en, this message translates to:
/// **'Docked - Center'**
String get bottomAppBarPositionDockedCenter;
/// A setting for the position of the floating action button in the bottom app bar that places the button above the bar and aligns it at the end.
///
/// In en, this message translates to:
/// **'Floating - End'**
String get bottomAppBarPositionFloatingEnd;
/// A setting for the position of the floating action button in the bottom app bar that places the button above the bar and aligns it in the center.
///
/// In en, this message translates to:
/// **'Floating - Center'**
String get bottomAppBarPositionFloatingCenter;
/// Title for the material banner component demo.
///
/// In en, this message translates to:
/// **'Banner'**
String get demoBannerTitle;
/// Subtitle for the material banner component demo.
///
/// In en, this message translates to:
/// **'Displaying a banner within a list'**
String get demoBannerSubtitle;
/// Description for the material banner component demo.
///
/// In en, this message translates to:
/// **'A banner displays an important, succinct message, and provides actions for users to address (or dismiss the banner). A user action is required for it to be dismissed.'**
String get demoBannerDescription;
/// Title for the material bottom navigation component demo.
///
/// In en, this message translates to:
/// **'Bottom navigation'**
String get demoBottomNavigationTitle;
/// Subtitle for the material bottom navigation component demo.
///
/// In en, this message translates to:
/// **'Bottom navigation with cross-fading views'**
String get demoBottomNavigationSubtitle;
/// Option title for bottom navigation with persistent labels.
///
/// In en, this message translates to:
/// **'Persistent labels'**
String get demoBottomNavigationPersistentLabels;
/// Option title for bottom navigation with only a selected label.
///
/// In en, this message translates to:
/// **'Selected label'**
String get demoBottomNavigationSelectedLabel;
/// Description for the material bottom navigation component demo.
///
/// In en, this message translates to:
/// **'Bottom navigation bars display three to five destinations at the bottom of a screen. Each destination is represented by an icon and an optional text label. When a bottom navigation icon is tapped, the user is taken to the top-level navigation destination associated with that icon.'**
String get demoBottomNavigationDescription;
/// Title for the material buttons component demo.
///
/// In en, this message translates to:
/// **'Buttons'**
String get demoButtonTitle;
/// Subtitle for the material buttons component demo.
///
/// In en, this message translates to:
/// **'Text, elevated, outlined, and more'**
String get demoButtonSubtitle;
/// Title for the text button component demo.
///
/// In en, this message translates to:
/// **'Text Button'**
String get demoTextButtonTitle;
/// Description for the text button component demo.
///
/// In en, this message translates to:
/// **'A text button displays an ink splash on press but does not lift. Use text buttons on toolbars, in dialogs and inline with padding'**
String get demoTextButtonDescription;
/// Title for the elevated button component demo.
///
/// In en, this message translates to:
/// **'Elevated Button'**
String get demoElevatedButtonTitle;
/// Description for the elevated button component demo.
///
/// In en, this message translates to:
/// **'Elevated buttons add dimension to mostly flat layouts. They emphasize functions on busy or wide spaces.'**
String get demoElevatedButtonDescription;
/// Title for the outlined button component demo.
///
/// In en, this message translates to:
/// **'Outlined Button'**
String get demoOutlinedButtonTitle;
/// Description for the outlined button component demo.
///
/// In en, this message translates to:
/// **'Outlined buttons become opaque and elevate when pressed. They are often paired with raised buttons to indicate an alternative, secondary action.'**
String get demoOutlinedButtonDescription;
/// Title for the toggle buttons component demo.
///
/// In en, this message translates to:
/// **'Toggle Buttons'**
String get demoToggleButtonTitle;
/// Description for the toggle buttons component demo.
///
/// In en, this message translates to:
/// **'Toggle buttons can be used to group related options. To emphasize groups of related toggle buttons, a group should share a common container'**
String get demoToggleButtonDescription;
/// Title for the floating action button component demo.
///
/// In en, this message translates to:
/// **'Floating Action Button'**
String get demoFloatingButtonTitle;
/// Description for the floating action button component demo.
///
/// In en, this message translates to:
/// **'A floating action button is a circular icon button that hovers over content to promote a primary action in the application.'**
String get demoFloatingButtonDescription;
/// Title for the material cards component demo.
///
/// In en, this message translates to:
/// **'Cards'**
String get demoCardTitle;
/// Subtitle for the material cards component demo.
///
/// In en, this message translates to:
/// **'Baseline cards with rounded corners'**
String get demoCardSubtitle;
/// Title for the material chips component demo.
///
/// In en, this message translates to:
/// **'Chips'**
String get demoChipTitle;
/// Description for the material cards component demo.
///
/// In en, this message translates to:
/// **'A card is a sheet of Material used to represent some related information, for example an album, a geographical location, a meal, contact details, etc.'**
String get demoCardDescription;
/// Subtitle for the material chips component demo.
///
/// In en, this message translates to:
/// **'Compact elements that represent an input, attribute, or action'**
String get demoChipSubtitle;
/// Title for the action chip component demo.
///
/// In en, this message translates to:
/// **'Action Chip'**
String get demoActionChipTitle;
/// Description for the action chip component demo.
///
/// In en, this message translates to:
/// **'Action chips are a set of options which trigger an action related to primary content. Action chips should appear dynamically and contextually in a UI.'**
String get demoActionChipDescription;
/// Title for the choice chip component demo.
///
/// In en, this message translates to:
/// **'Choice Chip'**
String get demoChoiceChipTitle;
/// Description for the choice chip component demo.
///
/// In en, this message translates to:
/// **'Choice chips represent a single choice from a set. Choice chips contain related descriptive text or categories.'**
String get demoChoiceChipDescription;
/// Title for the filter chip component demo.
///
/// In en, this message translates to:
/// **'Filter Chip'**
String get demoFilterChipTitle;
/// Description for the filter chip component demo.
///
/// In en, this message translates to:
/// **'Filter chips use tags or descriptive words as a way to filter content.'**
String get demoFilterChipDescription;
/// Title for the input chip component demo.
///
/// In en, this message translates to:
/// **'Input Chip'**
String get demoInputChipTitle;
/// Description for the input chip component demo.
///
/// In en, this message translates to:
/// **'Input chips represent a complex piece of information, such as an entity (person, place, or thing) or conversational text, in a compact form.'**
String get demoInputChipDescription;
/// Title for the material data table component demo.
///
/// In en, this message translates to:
/// **'Data Tables'**
String get demoDataTableTitle;
/// Subtitle for the material data table component demo.
///
/// In en, this message translates to:
/// **'Rows and columns of information'**
String get demoDataTableSubtitle;
/// Description for the material data table component demo.
///
/// In en, this message translates to:
/// **'Data tables display information in a grid-like format of rows and columns. They organize information in a way that\'s easy to scan, so that users can look for patterns and insights.'**
String get demoDataTableDescription;
/// Header for the data table component demo about nutrition.
///
/// In en, this message translates to:
/// **'Nutrition'**
String get dataTableHeader;
/// Column header for desserts.
///
/// In en, this message translates to:
/// **'Dessert (1 serving)'**
String get dataTableColumnDessert;
/// Column header for number of calories.
///
/// In en, this message translates to:
/// **'Calories'**
String get dataTableColumnCalories;
/// Column header for number of grams of fat.
///
/// In en, this message translates to:
/// **'Fat (g)'**
String get dataTableColumnFat;
/// Column header for number of grams of carbs.
///
/// In en, this message translates to:
/// **'Carbs (g)'**
String get dataTableColumnCarbs;
/// Column header for number of grams of protein.
///
/// In en, this message translates to:
/// **'Protein (g)'**
String get dataTableColumnProtein;
/// Column header for number of milligrams of sodium.
///
/// In en, this message translates to:
/// **'Sodium (mg)'**
String get dataTableColumnSodium;
/// Column header for daily percentage of calcium.
///
/// In en, this message translates to:
/// **'Calcium (%)'**
String get dataTableColumnCalcium;
/// Column header for daily percentage of iron.
///
/// In en, this message translates to:
/// **'Iron (%)'**
String get dataTableColumnIron;
/// Column row for frozen yogurt.
///
/// In en, this message translates to:
/// **'Frozen yogurt'**
String get dataTableRowFrozenYogurt;
/// Column row for Ice cream sandwich.
///
/// In en, this message translates to:
/// **'Ice cream sandwich'**
String get dataTableRowIceCreamSandwich;
/// Column row for Eclair.
///
/// In en, this message translates to:
/// **'Eclair'**
String get dataTableRowEclair;
/// Column row for Cupcake.
///
/// In en, this message translates to:
/// **'Cupcake'**
String get dataTableRowCupcake;
/// Column row for Gingerbread.
///
/// In en, this message translates to:
/// **'Gingerbread'**
String get dataTableRowGingerbread;
/// Column row for Jelly bean.
///
/// In en, this message translates to:
/// **'Jelly bean'**
String get dataTableRowJellyBean;
/// Column row for Lollipop.
///
/// In en, this message translates to:
/// **'Lollipop'**
String get dataTableRowLollipop;
/// Column row for Honeycomb.
///
/// In en, this message translates to:
/// **'Honeycomb'**
String get dataTableRowHoneycomb;
/// Column row for Donut.
///
/// In en, this message translates to:
/// **'Donut'**
String get dataTableRowDonut;
/// Column row for Apple pie.
///
/// In en, this message translates to:
/// **'Apple pie'**
String get dataTableRowApplePie;
/// A dessert with sugar on it. The parameter is some type of dessert.
///
/// In en, this message translates to:
/// **'{value} with sugar'**
String dataTableRowWithSugar(Object value);
/// A dessert with honey on it. The parameter is some type of dessert.
///
/// In en, this message translates to:
/// **'{value} with honey'**
String dataTableRowWithHoney(Object value);
/// Title for the material dialog component demo.
///
/// In en, this message translates to:
/// **'Dialogs'**
String get demoDialogTitle;
/// Subtitle for the material dialog component demo.
///
/// In en, this message translates to:
/// **'Simple, alert, and fullscreen'**
String get demoDialogSubtitle;
/// Title for the alert dialog component demo.
///
/// In en, this message translates to:
/// **'Alert'**
String get demoAlertDialogTitle;
/// Description for the alert dialog component demo.
///
/// In en, this message translates to:
/// **'An alert dialog informs the user about situations that require acknowledgement. An alert dialog has an optional title and an optional list of actions.'**
String get demoAlertDialogDescription;
/// Title for the alert dialog with title component demo.
///
/// In en, this message translates to:
/// **'Alert With Title'**
String get demoAlertTitleDialogTitle;
/// Title for the simple dialog component demo.
///
/// In en, this message translates to:
/// **'Simple'**
String get demoSimpleDialogTitle;
/// Description for the simple dialog component demo.
///
/// In en, this message translates to:
/// **'A simple dialog offers the user a choice between several options. A simple dialog has an optional title that is displayed above the choices.'**
String get demoSimpleDialogDescription;
/// Title for the divider component demo.
///
/// In en, this message translates to:
/// **'Divider'**
String get demoDividerTitle;
/// Subtitle for the divider component demo.
///
/// In en, this message translates to:
/// **'A divider is a thin line that groups content in lists and layouts.'**
String get demoDividerSubtitle;
/// Description for the divider component demo.
///
/// In en, this message translates to:
/// **'Dividers can be used in lists, drawers, and elsewhere to separate content.'**
String get demoDividerDescription;
/// Title for the vertical divider component demo.
///
/// In en, this message translates to:
/// **'Vertical Divider'**
String get demoVerticalDividerTitle;
/// Title for the grid lists component demo.
///
/// In en, this message translates to:
/// **'Grid Lists'**
String get demoGridListsTitle;
/// Subtitle for the grid lists component demo.
///
/// In en, this message translates to:
/// **'Row and column layout'**
String get demoGridListsSubtitle;
/// Description for the grid lists component demo.
///
/// In en, this message translates to:
/// **'Grid Lists are best suited for presenting homogeneous data, typically images. Each item in a grid list is called a tile.'**
String get demoGridListsDescription;
/// Title for the grid lists image-only component demo.
///
/// In en, this message translates to:
/// **'Image only'**
String get demoGridListsImageOnlyTitle;
/// Title for the grid lists component demo with headers on each tile.
///
/// In en, this message translates to:
/// **'With header'**
String get demoGridListsHeaderTitle;
/// Title for the grid lists component demo with footers on each tile.
///
/// In en, this message translates to:
/// **'With footer'**
String get demoGridListsFooterTitle;
/// Title for the sliders component demo.
///
/// In en, this message translates to:
/// **'Sliders'**
String get demoSlidersTitle;
/// Short description for the sliders component demo.
///
/// In en, this message translates to:
/// **'Widgets for selecting a value by swiping'**
String get demoSlidersSubtitle;
/// Description for the sliders demo.
///
/// In en, this message translates to:
/// **'Sliders reflect a range of values along a bar, from which users may select a single value. They are ideal for adjusting settings such as volume, brightness, or applying image filters.'**
String get demoSlidersDescription;
/// Title for the range sliders component demo.
///
/// In en, this message translates to:
/// **'Range Sliders'**
String get demoRangeSlidersTitle;
/// Description for the range sliders demo.
///
/// In en, this message translates to:
/// **'Sliders reflect a range of values along a bar. They can have icons on both ends of the bar that reflect a range of values. They are ideal for adjusting settings such as volume, brightness, or applying image filters.'**
String get demoRangeSlidersDescription;
/// Title for the custom sliders component demo.
///
/// In en, this message translates to:
/// **'Custom Sliders'**
String get demoCustomSlidersTitle;
/// Description for the custom sliders demo.
///
/// In en, this message translates to:
/// **'Sliders reflect a range of values along a bar, from which users may select a single value or range of values. The sliders can be themed and customized.'**
String get demoCustomSlidersDescription;
/// Text to describe a slider has a continuous value with an editable numerical value.
///
/// In en, this message translates to:
/// **'Continuous with Editable Numerical Value'**
String get demoSlidersContinuousWithEditableNumericalValue;
/// Text to describe that we have a slider with discrete values.
///
/// In en, this message translates to:
/// **'Discrete'**
String get demoSlidersDiscrete;
/// Text to describe that we have a slider with discrete values and a custom theme.
///
/// In en, this message translates to:
/// **'Discrete Slider with Custom Theme'**
String get demoSlidersDiscreteSliderWithCustomTheme;
/// Text to describe that we have a range slider with continuous values and a custom theme.
///
/// In en, this message translates to:
/// **'Continuous Range Slider with Custom Theme'**
String get demoSlidersContinuousRangeSliderWithCustomTheme;
/// Text to describe that we have a slider with continuous values.
///
/// In en, this message translates to:
/// **'Continuous'**
String get demoSlidersContinuous;
/// Label for input field that has an editable numerical value.
///
/// In en, this message translates to:
/// **'Editable numerical value'**
String get demoSlidersEditableNumericalValue;
/// Title for the menu component demo.
///
/// In en, this message translates to:
/// **'Menu'**
String get demoMenuTitle;
/// Title for the context menu component demo.
///
/// In en, this message translates to:
/// **'Context menu'**
String get demoContextMenuTitle;
/// Title for the sectioned menu component demo.
///
/// In en, this message translates to:
/// **'Sectioned menu'**
String get demoSectionedMenuTitle;
/// Title for the simple menu component demo.
///
/// In en, this message translates to:
/// **'Simple menu'**
String get demoSimpleMenuTitle;
/// Title for the checklist menu component demo.
///
/// In en, this message translates to:
/// **'Checklist menu'**
String get demoChecklistMenuTitle;
/// Short description for the menu component demo.
///
/// In en, this message translates to:
/// **'Menu buttons and simple menus'**
String get demoMenuSubtitle;
/// Description for the menu demo.
///
/// In en, this message translates to:
/// **'A menu displays a list of choices on a temporary surface. They appear when users interact with a button, action, or other control.'**
String get demoMenuDescription;
/// The first item in a menu.
///
/// In en, this message translates to:
/// **'Menu item one'**
String get demoMenuItemValueOne;
/// The second item in a menu.
///
/// In en, this message translates to:
/// **'Menu item two'**
String get demoMenuItemValueTwo;
/// The third item in a menu.
///
/// In en, this message translates to:
/// **'Menu item three'**
String get demoMenuItemValueThree;
/// The number one.
///
/// In en, this message translates to:
/// **'One'**
String get demoMenuOne;
/// The number two.
///
/// In en, this message translates to:
/// **'Two'**
String get demoMenuTwo;
/// The number three.
///
/// In en, this message translates to:
/// **'Three'**
String get demoMenuThree;
/// The number four.
///
/// In en, this message translates to:
/// **'Four'**
String get demoMenuFour;
/// Label next to a button that opens a menu. A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'An item with a context menu'**
String get demoMenuAnItemWithAContextMenuButton;
/// Text label for a context menu item. A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'Context menu item one'**
String get demoMenuContextMenuItemOne;
/// Text label for a disabled menu item. A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'Disabled menu item'**
String get demoMenuADisabledMenuItem;
/// Text label for a context menu item three. A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'Context menu item three'**
String get demoMenuContextMenuItemThree;
/// Label next to a button that opens a sectioned menu . A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'An item with a sectioned menu'**
String get demoMenuAnItemWithASectionedMenu;
/// Button to preview content.
///
/// In en, this message translates to:
/// **'Preview'**
String get demoMenuPreview;
/// Button to share content.
///
/// In en, this message translates to:
/// **'Share'**
String get demoMenuShare;
/// Button to get link for content.
///
/// In en, this message translates to:
/// **'Get link'**
String get demoMenuGetLink;
/// Button to remove content.
///
/// In en, this message translates to:
/// **'Remove'**
String get demoMenuRemove;
/// A text to show what value was selected.
///
/// In en, this message translates to:
/// **'Selected: {value}'**
String demoMenuSelected(Object value);
/// A text to show what value was checked.
///
/// In en, this message translates to:
/// **'Checked: {value}'**
String demoMenuChecked(Object value);
/// Title for the material drawer component demo.
///
/// In en, this message translates to:
/// **'Navigation Drawer'**
String get demoNavigationDrawerTitle;
/// Subtitle for the material drawer component demo.
///
/// In en, this message translates to:
/// **'Displaying a drawer within appbar'**
String get demoNavigationDrawerSubtitle;
/// Description for the material drawer component demo.
///
/// In en, this message translates to:
/// **'A Material Design panel that slides in horizontally from the edge of the screen to show navigation links in an application.'**
String get demoNavigationDrawerDescription;
/// Demo username for navigation drawer.
///
/// In en, this message translates to:
/// **'User Name'**
String get demoNavigationDrawerUserName;
/// Demo email for navigation drawer.
///
/// In en, this message translates to:
/// **'[email protected]'**
String get demoNavigationDrawerUserEmail;
/// Drawer Item One.
///
/// In en, this message translates to:
/// **'Item One'**
String get demoNavigationDrawerToPageOne;
/// Drawer Item Two.
///
/// In en, this message translates to:
/// **'Item Two'**
String get demoNavigationDrawerToPageTwo;
/// Description to open navigation drawer.
///
/// In en, this message translates to:
/// **'Swipe from the edge or tap the upper-left icon to see the drawer'**
String get demoNavigationDrawerText;
/// Title for the material Navigation Rail component demo.
///
/// In en, this message translates to:
/// **'Navigation Rail'**
String get demoNavigationRailTitle;
/// Subtitle for the material Navigation Rail component demo.
///
/// In en, this message translates to:
/// **'Displaying a Navigation Rail within an app'**
String get demoNavigationRailSubtitle;
/// Description for the material Navigation Rail component demo.
///
/// In en, this message translates to:
/// **'A material widget that is meant to be displayed at the left or right of an app to navigate between a small number of views, typically between three and five.'**
String get demoNavigationRailDescription;
/// Navigation Rail destination first label.
///
/// In en, this message translates to:
/// **'First'**
String get demoNavigationRailFirst;
/// Navigation Rail destination second label.
///
/// In en, this message translates to:
/// **'Second'**
String get demoNavigationRailSecond;
/// Navigation Rail destination Third label.
///
/// In en, this message translates to:
/// **'Third'**
String get demoNavigationRailThird;
/// Label next to a button that opens a simple menu. A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'An item with a simple menu'**
String get demoMenuAnItemWithASimpleMenu;
/// Label next to a button that opens a checklist menu. A menu displays a list of choices on a temporary surface. Used as an example in a demo.
///
/// In en, this message translates to:
/// **'An item with a checklist menu'**
String get demoMenuAnItemWithAChecklistMenu;
/// Title for the fullscreen dialog component demo.
///
/// In en, this message translates to:
/// **'Fullscreen'**
String get demoFullscreenDialogTitle;
/// Description for the fullscreen dialog component demo.
///
/// In en, this message translates to:
/// **'The fullscreenDialog property specifies whether the incoming page is a fullscreen modal dialog'**
String get demoFullscreenDialogDescription;
/// Title for the cupertino activity indicator component demo.
///
/// In en, this message translates to:
/// **'Activity indicator'**
String get demoCupertinoActivityIndicatorTitle;
/// Subtitle for the cupertino activity indicator component demo.
///
/// In en, this message translates to:
/// **'iOS-style activity indicators'**
String get demoCupertinoActivityIndicatorSubtitle;
/// Description for the cupertino activity indicator component demo.
///
/// In en, this message translates to:
/// **'An iOS-style activity indicator that spins clockwise.'**
String get demoCupertinoActivityIndicatorDescription;
/// Title for the cupertino buttons component demo.
///
/// In en, this message translates to:
/// **'Buttons'**
String get demoCupertinoButtonsTitle;
/// Subtitle for the cupertino buttons component demo.
///
/// In en, this message translates to:
/// **'iOS-style buttons'**
String get demoCupertinoButtonsSubtitle;
/// Description for the cupertino buttons component demo.
///
/// In en, this message translates to:
/// **'An iOS-style button. It takes in text and/or an icon that fades out and in on touch. May optionally have a background.'**
String get demoCupertinoButtonsDescription;
/// Title for the cupertino context menu component demo.
///
/// In en, this message translates to:
/// **'Context Menu'**
String get demoCupertinoContextMenuTitle;
/// Subtitle for the cupertino context menu component demo.
///
/// In en, this message translates to:
/// **'iOS-style context menu'**
String get demoCupertinoContextMenuSubtitle;
/// Description for the cupertino context menu component demo.
///
/// In en, this message translates to:
/// **'An iOS-style full screen contextual menu that appears when an element is long-pressed.'**
String get demoCupertinoContextMenuDescription;
/// Context menu list item one
///
/// In en, this message translates to:
/// **'Action one'**
String get demoCupertinoContextMenuActionOne;
/// Context menu list item two
///
/// In en, this message translates to:
/// **'Action two'**
String get demoCupertinoContextMenuActionTwo;
/// Context menu text.
///
/// In en, this message translates to:
/// **'Tap and hold the Flutter logo to see the context menu.'**
String get demoCupertinoContextMenuActionText;
/// Title for the cupertino alerts component demo.
///
/// In en, this message translates to:
/// **'Alerts'**
String get demoCupertinoAlertsTitle;
/// Subtitle for the cupertino alerts component demo.
///
/// In en, this message translates to:
/// **'iOS-style alert dialogs'**
String get demoCupertinoAlertsSubtitle;
/// Title for the cupertino alert component demo.
///
/// In en, this message translates to:
/// **'Alert'**
String get demoCupertinoAlertTitle;
/// Description for the cupertino alert component demo.
///
/// In en, this message translates to:
/// **'An alert dialog informs the user about situations that require acknowledgement. An alert dialog has an optional title, optional content, and an optional list of actions. The title is displayed above the content and the actions are displayed below the content.'**
String get demoCupertinoAlertDescription;
/// Title for the cupertino alert with title component demo.
///
/// In en, this message translates to:
/// **'Alert With Title'**
String get demoCupertinoAlertWithTitleTitle;
/// Title for the cupertino alert with buttons component demo.
///
/// In en, this message translates to:
/// **'Alert With Buttons'**
String get demoCupertinoAlertButtonsTitle;
/// Title for the cupertino alert buttons only component demo.
///
/// In en, this message translates to:
/// **'Alert Buttons Only'**
String get demoCupertinoAlertButtonsOnlyTitle;
/// Title for the cupertino action sheet component demo.
///
/// In en, this message translates to:
/// **'Action Sheet'**
String get demoCupertinoActionSheetTitle;
/// Description for the cupertino action sheet component demo.
///
/// In en, this message translates to:
/// **'An action sheet is a specific style of alert that presents the user with a set of two or more choices related to the current context. An action sheet can have a title, an additional message, and a list of actions.'**
String get demoCupertinoActionSheetDescription;
/// Title for the cupertino navigation bar component demo.
///
/// In en, this message translates to:
/// **'Navigation bar'**
String get demoCupertinoNavigationBarTitle;
/// Subtitle for the cupertino navigation bar component demo.
///
/// In en, this message translates to:
/// **'iOS-style navigation bar'**
String get demoCupertinoNavigationBarSubtitle;
/// Description for the cupertino navigation bar component demo.
///
/// In en, this message translates to:
/// **'An iOS-styled navigation bar. The navigation bar is a toolbar that minimally consists of a page title, in the middle of the toolbar.'**
String get demoCupertinoNavigationBarDescription;
/// Title for the cupertino pickers component demo.
///
/// In en, this message translates to:
/// **'Pickers'**
String get demoCupertinoPickerTitle;
/// Subtitle for the cupertino pickers component demo.
///
/// In en, this message translates to:
/// **'iOS-style pickers'**
String get demoCupertinoPickerSubtitle;
/// Description for the cupertino pickers component demo.
///
/// In en, this message translates to:
/// **'An iOS-style picker widget that can be used to select strings, dates, times, or both date and time.'**
String get demoCupertinoPickerDescription;
/// Label to open a countdown timer picker.
///
/// In en, this message translates to:
/// **'Timer'**
String get demoCupertinoPickerTimer;
/// Label to open an iOS picker.
///
/// In en, this message translates to:
/// **'Picker'**
String get demoCupertinoPicker;
/// Label to open a date picker.
///
/// In en, this message translates to:
/// **'Date'**
String get demoCupertinoPickerDate;
/// Label to open a time picker.
///
/// In en, this message translates to:
/// **'Time'**
String get demoCupertinoPickerTime;
/// Label to open a date and time picker.
///
/// In en, this message translates to:
/// **'Date and Time'**
String get demoCupertinoPickerDateTime;
/// Title for the cupertino pull-to-refresh component demo.
///
/// In en, this message translates to:
/// **'Pull to refresh'**
String get demoCupertinoPullToRefreshTitle;
/// Subtitle for the cupertino pull-to-refresh component demo.
///
/// In en, this message translates to:
/// **'iOS-style pull to refresh control'**
String get demoCupertinoPullToRefreshSubtitle;
/// Description for the cupertino pull-to-refresh component demo.
///
/// In en, this message translates to:
/// **'A widget implementing the iOS-style pull to refresh content control.'**
String get demoCupertinoPullToRefreshDescription;
/// Title for the cupertino segmented control component demo.
///
/// In en, this message translates to:
/// **'Segmented control'**
String get demoCupertinoSegmentedControlTitle;
/// Subtitle for the cupertino segmented control component demo.
///
/// In en, this message translates to:
/// **'iOS-style segmented control'**
String get demoCupertinoSegmentedControlSubtitle;
/// Description for the cupertino segmented control component demo.
///
/// In en, this message translates to:
/// **'Used to select between a number of mutually exclusive options. When one option in the segmented control is selected, the other options in the segmented control cease to be selected.'**
String get demoCupertinoSegmentedControlDescription;
/// Title for the cupertino slider component demo.
///
/// In en, this message translates to:
/// **'Slider'**
String get demoCupertinoSliderTitle;
/// Subtitle for the cupertino slider component demo.
///
/// In en, this message translates to:
/// **'iOS-style slider'**
String get demoCupertinoSliderSubtitle;
/// Description for the cupertino slider component demo.
///
/// In en, this message translates to:
/// **'A slider can be used to select from either a continuous or a discrete set of values.'**
String get demoCupertinoSliderDescription;
/// A label for a continuous slider that indicates what value it is set to.
///
/// In en, this message translates to:
/// **'Continuous: {value}'**
String demoCupertinoSliderContinuous(Object value);
/// A label for a discrete slider that indicates what value it is set to.
///
/// In en, this message translates to:
/// **'Discrete: {value}'**
String demoCupertinoSliderDiscrete(Object value);
/// Subtitle for the cupertino switch component demo.
///
/// In en, this message translates to:
/// **'iOS-style switch'**
String get demoCupertinoSwitchSubtitle;
/// Description for the cupertino switch component demo.
///
/// In en, this message translates to:
/// **'A switch is used to toggle the on/off state of a single setting.'**
String get demoCupertinoSwitchDescription;
/// Title for the cupertino bottom tab bar demo.
///
/// In en, this message translates to:
/// **'Tab bar'**
String get demoCupertinoTabBarTitle;
/// Subtitle for the cupertino bottom tab bar demo.
///
/// In en, this message translates to:
/// **'iOS-style bottom tab bar'**
String get demoCupertinoTabBarSubtitle;
/// Description for the cupertino bottom tab bar demo.
///
/// In en, this message translates to:
/// **'An iOS-style bottom navigation tab bar. Displays multiple tabs with one tab being active, the first tab by default.'**
String get demoCupertinoTabBarDescription;
/// Title for the home tab in the bottom tab bar demo.
///
/// In en, this message translates to:
/// **'Home'**
String get cupertinoTabBarHomeTab;
/// Title for the chat tab in the bottom tab bar demo.
///
/// In en, this message translates to:
/// **'Chat'**
String get cupertinoTabBarChatTab;
/// Title for the profile tab in the bottom tab bar demo.
///
/// In en, this message translates to:
/// **'Profile'**
String get cupertinoTabBarProfileTab;
/// Title for the cupertino text field demo.
///
/// In en, this message translates to:
/// **'Text fields'**
String get demoCupertinoTextFieldTitle;
/// Subtitle for the cupertino text field demo.
///
/// In en, this message translates to:
/// **'iOS-style text fields'**
String get demoCupertinoTextFieldSubtitle;
/// Description for the cupertino text field demo.
///
/// In en, this message translates to:
/// **'A text field lets the user enter text, either with a hardware keyboard or with an onscreen keyboard.'**
String get demoCupertinoTextFieldDescription;
/// The placeholder for a text field where a user would enter their PIN number.
///
/// In en, this message translates to:
/// **'PIN'**
String get demoCupertinoTextFieldPIN;
/// Title for the cupertino search text field demo.
///
/// In en, this message translates to:
/// **'Search text field'**
String get demoCupertinoSearchTextFieldTitle;
/// Subtitle for the cupertino search text field demo.
///
/// In en, this message translates to:
/// **'iOS-style search text field'**
String get demoCupertinoSearchTextFieldSubtitle;
/// Description for the cupertino search text field demo.
///
/// In en, this message translates to:
/// **'A search text field that lets the user search by entering text, and that can offer and filter suggestions.'**
String get demoCupertinoSearchTextFieldDescription;
/// The placeholder for a search text field demo.
///
/// In en, this message translates to:
/// **'Enter some text'**
String get demoCupertinoSearchTextFieldPlaceholder;
/// Title for the cupertino scrollbar demo.
///
/// In en, this message translates to:
/// **'Scrollbar'**
String get demoCupertinoScrollbarTitle;
/// Subtitle for the cupertino scrollbar demo.
///
/// In en, this message translates to:
/// **'iOS-style scrollbar'**
String get demoCupertinoScrollbarSubtitle;
/// Description for the cupertino scrollbar demo.
///
/// In en, this message translates to:
/// **'A scrollbar that wraps the given child'**
String get demoCupertinoScrollbarDescription;
/// Title for the motion demo.
///
/// In en, this message translates to:
/// **'Motion'**
String get demoMotionTitle;
/// Subtitle for the motion demo.
///
/// In en, this message translates to:
/// **'All of the predefined transition patterns'**
String get demoMotionSubtitle;
/// Instructions for the container transform demo located in the app bar.
///
/// In en, this message translates to:
/// **'Cards, Lists & FAB'**
String get demoContainerTransformDemoInstructions;
/// Instructions for the shared x axis demo located in the app bar.
///
/// In en, this message translates to:
/// **'Next and Back Buttons'**
String get demoSharedXAxisDemoInstructions;
/// Instructions for the shared y axis demo located in the app bar.
///
/// In en, this message translates to:
/// **'Sort by \"Recently Played\"'**
String get demoSharedYAxisDemoInstructions;
/// Instructions for the shared z axis demo located in the app bar.
///
/// In en, this message translates to:
/// **'Settings icon button'**
String get demoSharedZAxisDemoInstructions;
/// Instructions for the fade through demo located in the app bar.
///
/// In en, this message translates to:
/// **'Bottom navigation'**
String get demoFadeThroughDemoInstructions;
/// Instructions for the fade scale demo located in the app bar.
///
/// In en, this message translates to:
/// **'Modal and FAB'**
String get demoFadeScaleDemoInstructions;
/// Title for the container transform demo.
///
/// In en, this message translates to:
/// **'Container Transform'**
String get demoContainerTransformTitle;
/// Description for the container transform demo.
///
/// In en, this message translates to:
/// **'The container transform pattern is designed for transitions between UI elements that include a container. This pattern creates a visible connection between two UI elements'**
String get demoContainerTransformDescription;
/// Title for the container transform modal bottom sheet.
///
/// In en, this message translates to:
/// **'Fade mode'**
String get demoContainerTransformModalBottomSheetTitle;
/// Description for container transform fade type setting.
///
/// In en, this message translates to:
/// **'FADE'**
String get demoContainerTransformTypeFade;
/// Description for container transform fade through type setting.
///
/// In en, this message translates to:
/// **'FADE THROUGH'**
String get demoContainerTransformTypeFadeThrough;
/// The placeholder for the motion demos title properties.
///
/// In en, this message translates to:
/// **'Title'**
String get demoMotionPlaceholderTitle;
/// The placeholder for the motion demos subtitle properties.
///
/// In en, this message translates to:
/// **'Secondary text'**
String get demoMotionPlaceholderSubtitle;
/// The placeholder for the motion demos shortened subtitle properties.
///
/// In en, this message translates to:
/// **'Secondary'**
String get demoMotionSmallPlaceholderSubtitle;
/// The title for the details page in the motion demos.
///
/// In en, this message translates to:
/// **'Details Page'**
String get demoMotionDetailsPageTitle;
/// The title for a list tile in the motion demos.
///
/// In en, this message translates to:
/// **'List item'**
String get demoMotionListTileTitle;
/// Description for the shared y axis demo.
///
/// In en, this message translates to:
/// **'The shared axis pattern is used for transitions between the UI elements that have a spatial or navigational relationship. This pattern uses a shared transformation on the x, y, or z axis to reinforce the relationship between elements.'**
String get demoSharedAxisDescription;
/// Title for the shared x axis demo.
///
/// In en, this message translates to:
/// **'Shared x-axis'**
String get demoSharedXAxisTitle;
/// Button text for back button in the shared x axis demo.
///
/// In en, this message translates to:
/// **'BACK'**
String get demoSharedXAxisBackButtonText;
/// Button text for the next button in the shared x axis demo.
///
/// In en, this message translates to:
/// **'NEXT'**
String get demoSharedXAxisNextButtonText;
/// Title for course selection page in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Streamline your courses'**
String get demoSharedXAxisCoursePageTitle;
/// Subtitle for course selection page in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Bundled categories appear as groups in your feed. You can always change this later.'**
String get demoSharedXAxisCoursePageSubtitle;
/// Title for the Arts & Crafts course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Arts & Crafts'**
String get demoSharedXAxisArtsAndCraftsCourseTitle;
/// Title for the Business course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Business'**
String get demoSharedXAxisBusinessCourseTitle;
/// Title for the Illustration course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Illustration'**
String get demoSharedXAxisIllustrationCourseTitle;
/// Title for the Design course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Design'**
String get demoSharedXAxisDesignCourseTitle;
/// Title for the Culinary course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Culinary'**
String get demoSharedXAxisCulinaryCourseTitle;
/// Subtitle for a bundled course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Bundled'**
String get demoSharedXAxisBundledCourseSubtitle;
/// Subtitle for a individual course in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Shown Individually'**
String get demoSharedXAxisIndividualCourseSubtitle;
/// Welcome text for sign in page in the shared x axis demo. David Park is a name and does not need to be translated.
///
/// In en, this message translates to:
/// **'Hi David Park'**
String get demoSharedXAxisSignInWelcomeText;
/// Subtitle text for sign in page in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Sign in with your account'**
String get demoSharedXAxisSignInSubtitleText;
/// Label text for the sign in text field in the shared x axis demo.
///
/// In en, this message translates to:
/// **'Email or phone number'**
String get demoSharedXAxisSignInTextFieldLabel;
/// Button text for the forgot email button in the shared x axis demo.
///
/// In en, this message translates to:
/// **'FORGOT EMAIL?'**
String get demoSharedXAxisForgotEmailButtonText;
/// Button text for the create account button in the shared x axis demo.
///
/// In en, this message translates to:
/// **'CREATE ACCOUNT'**
String get demoSharedXAxisCreateAccountButtonText;
/// Title for the shared y axis demo.
///
/// In en, this message translates to:
/// **'Shared y-axis'**
String get demoSharedYAxisTitle;
/// Text for album count in the shared y axis demo.
///
/// In en, this message translates to:
/// **'268 albums'**
String get demoSharedYAxisAlbumCount;
/// Title for alphabetical sorting type in the shared y axis demo.
///
/// In en, this message translates to:
/// **'A-Z'**
String get demoSharedYAxisAlphabeticalSortTitle;
/// Title for recently played sorting type in the shared y axis demo.
///
/// In en, this message translates to:
/// **'Recently played'**
String get demoSharedYAxisRecentSortTitle;
/// Title for an AlbumTile in the shared y axis demo.
///
/// In en, this message translates to:
/// **'Album'**
String get demoSharedYAxisAlbumTileTitle;
/// Subtitle for an AlbumTile in the shared y axis demo.
///
/// In en, this message translates to:
/// **'Artist'**
String get demoSharedYAxisAlbumTileSubtitle;
/// Duration unit for an AlbumTile in the shared y axis demo.
///
/// In en, this message translates to:
/// **'min'**
String get demoSharedYAxisAlbumTileDurationUnit;
/// Title for the shared z axis demo.
///
/// In en, this message translates to:
/// **'Shared z-axis'**
String get demoSharedZAxisTitle;
/// Title for the settings page in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Settings'**
String get demoSharedZAxisSettingsPageTitle;
/// Title for burger recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Burger'**
String get demoSharedZAxisBurgerRecipeTitle;
/// Subtitle for the burger recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Burger recipe'**
String get demoSharedZAxisBurgerRecipeDescription;
/// Title for sandwich recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Sandwich'**
String get demoSharedZAxisSandwichRecipeTitle;
/// Subtitle for the sandwich recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Sandwich recipe'**
String get demoSharedZAxisSandwichRecipeDescription;
/// Title for dessert recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Dessert'**
String get demoSharedZAxisDessertRecipeTitle;
/// Subtitle for the dessert recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Dessert recipe'**
String get demoSharedZAxisDessertRecipeDescription;
/// Title for shrimp plate recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Shrimp'**
String get demoSharedZAxisShrimpPlateRecipeTitle;
/// Subtitle for the shrimp plate recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Shrimp plate recipe'**
String get demoSharedZAxisShrimpPlateRecipeDescription;
/// Title for crab plate recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Crab'**
String get demoSharedZAxisCrabPlateRecipeTitle;
/// Subtitle for the crab plate recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Crab plate recipe'**
String get demoSharedZAxisCrabPlateRecipeDescription;
/// Title for beef sandwich recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Beef Sandwich'**
String get demoSharedZAxisBeefSandwichRecipeTitle;
/// Subtitle for the beef sandwich recipe tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Beef Sandwich recipe'**
String get demoSharedZAxisBeefSandwichRecipeDescription;
/// Title for list of saved recipes in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Saved Recipes'**
String get demoSharedZAxisSavedRecipesListTitle;
/// Text label for profile setting tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Profile'**
String get demoSharedZAxisProfileSettingLabel;
/// Text label for notifications setting tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Notifications'**
String get demoSharedZAxisNotificationSettingLabel;
/// Text label for the privacy setting tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Privacy'**
String get demoSharedZAxisPrivacySettingLabel;
/// Text label for the help setting tile in the shared z axis demo.
///
/// In en, this message translates to:
/// **'Help'**
String get demoSharedZAxisHelpSettingLabel;
/// Title for the fade through demo.
///
/// In en, this message translates to:
/// **'Fade through'**
String get demoFadeThroughTitle;
/// Description for the fade through demo.
///
/// In en, this message translates to:
/// **'The fade through pattern is used for transitions between UI elements that do not have a strong relationship to each other.'**
String get demoFadeThroughDescription;
/// Text for albums bottom navigation bar destination in the fade through demo.
///
/// In en, this message translates to:
/// **'Albums'**
String get demoFadeThroughAlbumsDestination;
/// Text for photos bottom navigation bar destination in the fade through demo.
///
/// In en, this message translates to:
/// **'Photos'**
String get demoFadeThroughPhotosDestination;
/// Text for search bottom navigation bar destination in the fade through demo.
///
/// In en, this message translates to:
/// **'Search'**
String get demoFadeThroughSearchDestination;
/// Placeholder for example card title in the fade through demo.
///
/// In en, this message translates to:
/// **'123 photos'**
String get demoFadeThroughTextPlaceholder;
/// Title for the fade scale demo.
///
/// In en, this message translates to:
/// **'Fade'**
String get demoFadeScaleTitle;
/// Description for the fade scale demo.
///
/// In en, this message translates to:
/// **'The fade pattern is used for UI elements that enter or exit within the bounds of the screen, such as a dialog that fades in the center of the screen.'**
String get demoFadeScaleDescription;
/// Button text to show alert dialog in the fade scale demo.
///
/// In en, this message translates to:
/// **'SHOW MODAL'**
String get demoFadeScaleShowAlertDialogButton;
/// Button text to show fab in the fade scale demo.
///
/// In en, this message translates to:
/// **'SHOW FAB'**
String get demoFadeScaleShowFabButton;
/// Button text to hide fab in the fade scale demo.
///
/// In en, this message translates to:
/// **'HIDE FAB'**
String get demoFadeScaleHideFabButton;
/// Generic header for alert dialog in the fade scale demo.
///
/// In en, this message translates to:
/// **'Alert Dialog'**
String get demoFadeScaleAlertDialogHeader;
/// Button text for alert dialog cancel button in the fade scale demo.
///
/// In en, this message translates to:
/// **'CANCEL'**
String get demoFadeScaleAlertDialogCancelButton;
/// Button text for alert dialog discard button in the fade scale demo.
///
/// In en, this message translates to:
/// **'DISCARD'**
String get demoFadeScaleAlertDialogDiscardButton;
/// Title for the colors demo.
///
/// In en, this message translates to:
/// **'Colors'**
String get demoColorsTitle;
/// Subtitle for the colors demo.
///
/// In en, this message translates to:
/// **'All of the predefined colors'**
String get demoColorsSubtitle;
/// Description for the colors demo. Material Design should remain capitalized.
///
/// In en, this message translates to:
/// **'Color and color swatch constants which represent Material Design\'s color palette.'**
String get demoColorsDescription;
/// Title for the typography demo.
///
/// In en, this message translates to:
/// **'Typography'**
String get demoTypographyTitle;
/// Subtitle for the typography demo.
///
/// In en, this message translates to:
/// **'All of the predefined text styles'**
String get demoTypographySubtitle;
/// Description for the typography demo. Material Design should remain capitalized.
///
/// In en, this message translates to:
/// **'Definitions for the various typographical styles found in Material Design.'**
String get demoTypographyDescription;
/// Title for the 2D transformations demo.
///
/// In en, this message translates to:
/// **'2D transformations'**
String get demo2dTransformationsTitle;
/// Subtitle for the 2D transformations demo.
///
/// In en, this message translates to:
/// **'Pan and zoom'**
String get demo2dTransformationsSubtitle;
/// Description for the 2D transformations demo.
///
/// In en, this message translates to:
/// **'Tap to edit tiles, and use gestures to move around the scene. Drag to pan and pinch with two fingers to zoom. Press the reset button to return to the starting orientation.'**
String get demo2dTransformationsDescription;
/// Tooltip for a button to reset the transformations (scale, translation) for the 2D transformations demo.
///
/// In en, this message translates to:
/// **'Reset transformations'**
String get demo2dTransformationsResetTooltip;
/// Tooltip for a button to edit a tile.
///
/// In en, this message translates to:
/// **'Edit tile'**
String get demo2dTransformationsEditTooltip;
/// Text for a generic button.
///
/// In en, this message translates to:
/// **'BUTTON'**
String get buttonText;
/// Title for bottom sheet demo.
///
/// In en, this message translates to:
/// **'Bottom sheet'**
String get demoBottomSheetTitle;
/// Description for bottom sheet demo.
///
/// In en, this message translates to:
/// **'Persistent and modal bottom sheets'**
String get demoBottomSheetSubtitle;
/// Title for persistent bottom sheet demo.
///
/// In en, this message translates to:
/// **'Persistent bottom sheet'**
String get demoBottomSheetPersistentTitle;
/// Description for persistent bottom sheet demo.
///
/// In en, this message translates to:
/// **'A persistent bottom sheet shows information that supplements the primary content of the app. A persistent bottom sheet remains visible even when the user interacts with other parts of the app.'**
String get demoBottomSheetPersistentDescription;
/// Title for modal bottom sheet demo.
///
/// In en, this message translates to:
/// **'Modal bottom sheet'**
String get demoBottomSheetModalTitle;
/// Description for modal bottom sheet demo.
///
/// In en, this message translates to:
/// **'A modal bottom sheet is an alternative to a menu or a dialog and prevents the user from interacting with the rest of the app.'**
String get demoBottomSheetModalDescription;
/// Semantic label for add icon.
///
/// In en, this message translates to:
/// **'Add'**
String get demoBottomSheetAddLabel;
/// Button text to show bottom sheet.
///
/// In en, this message translates to:
/// **'SHOW BOTTOM SHEET'**
String get demoBottomSheetButtonText;
/// Generic header placeholder.
///
/// In en, this message translates to:
/// **'Header'**
String get demoBottomSheetHeader;
/// Generic item placeholder.
///
/// In en, this message translates to:
/// **'Item {value}'**
String demoBottomSheetItem(Object value);
/// Title for lists demo.
///
/// In en, this message translates to:
/// **'Lists'**
String get demoListsTitle;
/// Subtitle for lists demo.
///
/// In en, this message translates to:
/// **'Scrolling list layouts'**
String get demoListsSubtitle;
/// Description for lists demo. This describes what a single row in a list consists of.
///
/// In en, this message translates to:
/// **'A single fixed-height row that typically contains some text as well as a leading or trailing icon.'**
String get demoListsDescription;
/// Title for lists demo with only one line of text per row.
///
/// In en, this message translates to:
/// **'One Line'**
String get demoOneLineListsTitle;
/// Title for lists demo with two lines of text per row.
///
/// In en, this message translates to:
/// **'Two Lines'**
String get demoTwoLineListsTitle;
/// Text that appears in the second line of a list item.
///
/// In en, this message translates to:
/// **'Secondary text'**
String get demoListsSecondary;
/// Title for progress indicators demo.
///
/// In en, this message translates to:
/// **'Progress indicators'**
String get demoProgressIndicatorTitle;
/// Subtitle for progress indicators demo.
///
/// In en, this message translates to:
/// **'Linear, circular, indeterminate'**
String get demoProgressIndicatorSubtitle;
/// Title for circular progress indicator demo.
///
/// In en, this message translates to:
/// **'Circular Progress Indicator'**
String get demoCircularProgressIndicatorTitle;
/// Description for circular progress indicator demo.
///
/// In en, this message translates to:
/// **'A Material Design circular progress indicator, which spins to indicate that the application is busy.'**
String get demoCircularProgressIndicatorDescription;
/// Title for linear progress indicator demo.
///
/// In en, this message translates to:
/// **'Linear Progress Indicator'**
String get demoLinearProgressIndicatorTitle;
/// Description for linear progress indicator demo.
///
/// In en, this message translates to:
/// **'A Material Design linear progress indicator, also known as a progress bar.'**
String get demoLinearProgressIndicatorDescription;
/// Title for pickers demo.
///
/// In en, this message translates to:
/// **'Pickers'**
String get demoPickersTitle;
/// Subtitle for pickers demo.
///
/// In en, this message translates to:
/// **'Date and time selection'**
String get demoPickersSubtitle;
/// Title for date picker demo.
///
/// In en, this message translates to:
/// **'Date Picker'**
String get demoDatePickerTitle;
/// Description for date picker demo.
///
/// In en, this message translates to:
/// **'Shows a dialog containing a Material Design date picker.'**
String get demoDatePickerDescription;
/// Title for time picker demo.
///
/// In en, this message translates to:
/// **'Time Picker'**
String get demoTimePickerTitle;
/// Description for time picker demo.
///
/// In en, this message translates to:
/// **'Shows a dialog containing a Material Design time picker.'**
String get demoTimePickerDescription;
/// Title for date range picker demo.
///
/// In en, this message translates to:
/// **'Date Range Picker'**
String get demoDateRangePickerTitle;
/// Description for date range picker demo.
///
/// In en, this message translates to:
/// **'Shows a dialog containing a Material Design date range picker.'**
String get demoDateRangePickerDescription;
/// Button text to show the date or time picker in the demo.
///
/// In en, this message translates to:
/// **'SHOW PICKER'**
String get demoPickersShowPicker;
/// Title for tabs demo.
///
/// In en, this message translates to:
/// **'Tabs'**
String get demoTabsTitle;
/// Title for tabs demo with a tab bar that scrolls.
///
/// In en, this message translates to:
/// **'Scrolling'**
String get demoTabsScrollingTitle;
/// Title for tabs demo with a tab bar that doesn't scroll.
///
/// In en, this message translates to:
/// **'Non-scrolling'**
String get demoTabsNonScrollingTitle;
/// Subtitle for tabs demo.
///
/// In en, this message translates to:
/// **'Tabs with independently scrollable views'**
String get demoTabsSubtitle;
/// Description for tabs demo.
///
/// In en, this message translates to:
/// **'Tabs organize content across different screens, data sets, and other interactions.'**
String get demoTabsDescription;
/// Title for snackbars demo.
///
/// In en, this message translates to:
/// **'Snackbars'**
String get demoSnackbarsTitle;
/// Subtitle for snackbars demo.
///
/// In en, this message translates to:
/// **'Snackbars show messages at the bottom of the screen'**
String get demoSnackbarsSubtitle;
/// Description for snackbars demo.
///
/// In en, this message translates to:
/// **'Snackbars inform users of a process that an app has performed or will perform. They appear temporarily, towards the bottom of the screen. They shouldn\'t interrupt the user experience, and they don\'t require user input to disappear.'**
String get demoSnackbarsDescription;
/// Label for button to show a snackbar.
///
/// In en, this message translates to:
/// **'SHOW A SNACKBAR'**
String get demoSnackbarsButtonLabel;
/// Text to show on a snackbar.
///
/// In en, this message translates to:
/// **'This is a snackbar.'**
String get demoSnackbarsText;
/// Label for action button text on the snackbar.
///
/// In en, this message translates to:
/// **'ACTION'**
String get demoSnackbarsActionButtonLabel;
/// Text that appears when you press on a snackbars' action.
///
/// In en, this message translates to:
/// **'You pressed the snackbar action.'**
String get demoSnackbarsAction;
/// Title for selection controls demo.
///
/// In en, this message translates to:
/// **'Selection controls'**
String get demoSelectionControlsTitle;
/// Subtitle for selection controls demo.
///
/// In en, this message translates to:
/// **'Checkboxes, radio buttons, and switches'**
String get demoSelectionControlsSubtitle;
/// Title for the checkbox (selection controls) demo.
///
/// In en, this message translates to:
/// **'Checkbox'**
String get demoSelectionControlsCheckboxTitle;
/// Description for the checkbox (selection controls) demo.
///
/// In en, this message translates to:
/// **'Checkboxes allow the user to select multiple options from a set. A normal checkbox\'s value is true or false and a tristate checkbox\'s value can also be null.'**
String get demoSelectionControlsCheckboxDescription;
/// Title for the radio button (selection controls) demo.
///
/// In en, this message translates to:
/// **'Radio'**
String get demoSelectionControlsRadioTitle;
/// Description for the radio button (selection controls) demo.
///
/// In en, this message translates to:
/// **'Radio buttons allow the user to select one option from a set. Use radio buttons for exclusive selection if you think that the user needs to see all available options side-by-side.'**
String get demoSelectionControlsRadioDescription;
/// Title for the switches (selection controls) demo.
///
/// In en, this message translates to:
/// **'Switch'**
String get demoSelectionControlsSwitchTitle;
/// Description for the switches (selection controls) demo.
///
/// In en, this message translates to:
/// **'On/off switches toggle the state of a single settings option. The option that the switch controls, as well as the state it\'s in, should be made clear from the corresponding inline label.'**
String get demoSelectionControlsSwitchDescription;
/// Title for text fields demo.
///
/// In en, this message translates to:
/// **'Text fields'**
String get demoBottomTextFieldsTitle;
/// Title for text fields demo.
///
/// In en, this message translates to:
/// **'Text fields'**
String get demoTextFieldTitle;
/// Description for text fields demo.
///
/// In en, this message translates to:
/// **'Single line of editable text and numbers'**
String get demoTextFieldSubtitle;
/// Description for text fields demo.
///
/// In en, this message translates to:
/// **'Text fields allow users to enter text into a UI. They typically appear in forms and dialogs.'**
String get demoTextFieldDescription;
/// Label for show password icon.
///
/// In en, this message translates to:
/// **'Show password'**
String get demoTextFieldShowPasswordLabel;
/// Label for hide password icon.
///
/// In en, this message translates to:
/// **'Hide password'**
String get demoTextFieldHidePasswordLabel;
/// Text that shows up on form errors.
///
/// In en, this message translates to:
/// **'Please fix the errors in red before submitting.'**
String get demoTextFieldFormErrors;
/// Shows up as submission error if name is not given in the form.
///
/// In en, this message translates to:
/// **'Name is required.'**
String get demoTextFieldNameRequired;
/// Error that shows if non-alphabetical characters are given.
///
/// In en, this message translates to:
/// **'Please enter only alphabetical characters.'**
String get demoTextFieldOnlyAlphabeticalChars;
/// Error that shows up if non-valid non-US phone number is given.
///
/// In en, this message translates to:
/// **'(###) ###-#### - Enter a US phone number.'**
String get demoTextFieldEnterUSPhoneNumber;
/// Error that shows up if password is not given.
///
/// In en, this message translates to:
/// **'Please enter a password.'**
String get demoTextFieldEnterPassword;
/// Error that shows up, if the re-typed password does not match the already given password.
///
/// In en, this message translates to:
/// **'The passwords don\'t match'**
String get demoTextFieldPasswordsDoNotMatch;
/// Placeholder for name field in form.
///
/// In en, this message translates to:
/// **'What do people call you?'**
String get demoTextFieldWhatDoPeopleCallYou;
/// The label for a name input field that is required (hence the star).
///
/// In en, this message translates to:
/// **'Name*'**
String get demoTextFieldNameField;
/// Placeholder for when entering a phone number in a form.
///
/// In en, this message translates to:
/// **'Where can we reach you?'**
String get demoTextFieldWhereCanWeReachYou;
/// The label for a phone number input field that is required (hence the star).
///
/// In en, this message translates to:
/// **'Phone number*'**
String get demoTextFieldPhoneNumber;
/// The label for an email address input field.
///
/// In en, this message translates to:
/// **'Your email address'**
String get demoTextFieldYourEmailAddress;
/// The label for an email address input field
///
/// In en, this message translates to:
/// **'Email'**
String get demoTextFieldEmail;
/// The placeholder text for biography/life story input field.
///
/// In en, this message translates to:
/// **'Tell us about yourself (e.g., write down what you do or what hobbies you have)'**
String get demoTextFieldTellUsAboutYourself;
/// Helper text for biography/life story input field.
///
/// In en, this message translates to:
/// **'Keep it short, this is just a demo.'**
String get demoTextFieldKeepItShort;
/// The label for biography/life story input field.
///
/// In en, this message translates to:
/// **'Life story'**
String get demoTextFieldLifeStory;
/// The label for salary input field.
///
/// In en, this message translates to:
/// **'Salary'**
String get demoTextFieldSalary;
/// US currency, used as suffix in input field for salary.
///
/// In en, this message translates to:
/// **'USD'**
String get demoTextFieldUSD;
/// Helper text for password input field.
///
/// In en, this message translates to:
/// **'No more than 8 characters.'**
String get demoTextFieldNoMoreThan;
/// Label for password input field, that is required (hence the star).
///
/// In en, this message translates to:
/// **'Password*'**
String get demoTextFieldPassword;
/// Label for repeat password input field.
///
/// In en, this message translates to:
/// **'Re-type password*'**
String get demoTextFieldRetypePassword;
/// The submit button text for form.
///
/// In en, this message translates to:
/// **'SUBMIT'**
String get demoTextFieldSubmit;
/// Text that shows up when valid phone number and name is submitted in form.
///
/// In en, this message translates to:
/// **'{name} phone number is {phoneNumber}'**
String demoTextFieldNameHasPhoneNumber(Object name, Object phoneNumber);
/// Helper text to indicate that * means that it is a required field.
///
/// In en, this message translates to:
/// **'* indicates required field'**
String get demoTextFieldRequiredField;
/// Title for tooltip demo.
///
/// In en, this message translates to:
/// **'Tooltips'**
String get demoTooltipTitle;
/// Subtitle for tooltip demo.
///
/// In en, this message translates to:
/// **'Short message displayed on long press or hover'**
String get demoTooltipSubtitle;
/// Description for tooltip demo.
///
/// In en, this message translates to:
/// **'Tooltips provide text labels that help explain the function of a button or other user interface action. Tooltips display informative text when users hover over, focus on, or long press an element.'**
String get demoTooltipDescription;
/// Instructions for how to trigger a tooltip in the tooltip demo.
///
/// In en, this message translates to:
/// **'Long press or hover to display the tooltip.'**
String get demoTooltipInstructions;
/// Title for Comments tab of bottom navigation.
///
/// In en, this message translates to:
/// **'Comments'**
String get bottomNavigationCommentsTab;
/// Title for Calendar tab of bottom navigation.
///
/// In en, this message translates to:
/// **'Calendar'**
String get bottomNavigationCalendarTab;
/// Title for Account tab of bottom navigation.
///
/// In en, this message translates to:
/// **'Account'**
String get bottomNavigationAccountTab;
/// Title for Alarm tab of bottom navigation.
///
/// In en, this message translates to:
/// **'Alarm'**
String get bottomNavigationAlarmTab;
/// Title for Camera tab of bottom navigation.
///
/// In en, this message translates to:
/// **'Camera'**
String get bottomNavigationCameraTab;
/// Accessibility label for the content placeholder in the bottom navigation demo
///
/// In en, this message translates to:
/// **'Placeholder for {title} tab'**
String bottomNavigationContentPlaceholder(Object title);
/// Tooltip text for a create button.
///
/// In en, this message translates to:
/// **'Create'**
String get buttonTextCreate;
/// Message displayed after an option is selected from a dialog
///
/// In en, this message translates to:
/// **'You selected: \"{value}\"'**
String dialogSelectedOption(Object value);
/// A chip component to turn on the lights.
///
/// In en, this message translates to:
/// **'Turn on lights'**
String get chipTurnOnLights;
/// A chip component to select a small size.
///
/// In en, this message translates to:
/// **'Small'**
String get chipSmall;
/// A chip component to select a medium size.
///
/// In en, this message translates to:
/// **'Medium'**
String get chipMedium;
/// A chip component to select a large size.
///
/// In en, this message translates to:
/// **'Large'**
String get chipLarge;
/// A chip component to filter selection by elevators.
///
/// In en, this message translates to:
/// **'Elevator'**
String get chipElevator;
/// A chip component to filter selection by washers.
///
/// In en, this message translates to:
/// **'Washer'**
String get chipWasher;
/// A chip component to filter selection by fireplaces.
///
/// In en, this message translates to:
/// **'Fireplace'**
String get chipFireplace;
/// A chip component to that indicates a biking selection.
///
/// In en, this message translates to:
/// **'Biking'**
String get chipBiking;
/// Used in the title of the demos.
///
/// In en, this message translates to:
/// **'Demo'**
String get demo;
/// Used as semantic label for a BottomAppBar.
///
/// In en, this message translates to:
/// **'Bottom app bar'**
String get bottomAppBar;
/// Indicates the loading process.
///
/// In en, this message translates to:
/// **'Loading'**
String get loading;
/// Alert dialog message to discard draft.
///
/// In en, this message translates to:
/// **'Discard draft?'**
String get dialogDiscardTitle;
/// Alert dialog title to use location services.
///
/// In en, this message translates to:
/// **'Use Google\'s location service?'**
String get dialogLocationTitle;
/// Alert dialog description to use location services.
///
/// In en, this message translates to:
/// **'Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running.'**
String get dialogLocationDescription;
/// Alert dialog cancel option.
///
/// In en, this message translates to:
/// **'CANCEL'**
String get dialogCancel;
/// Alert dialog discard option.
///
/// In en, this message translates to:
/// **'DISCARD'**
String get dialogDiscard;
/// Alert dialog disagree option.
///
/// In en, this message translates to:
/// **'DISAGREE'**
String get dialogDisagree;
/// Alert dialog agree option.
///
/// In en, this message translates to:
/// **'AGREE'**
String get dialogAgree;
/// Alert dialog title for setting a backup account.
///
/// In en, this message translates to:
/// **'Set backup account'**
String get dialogSetBackup;
/// Alert dialog option for adding an account.
///
/// In en, this message translates to:
/// **'Add account'**
String get dialogAddAccount;
/// Button text to display a dialog.
///
/// In en, this message translates to:
/// **'SHOW DIALOG'**
String get dialogShow;
/// Title for full screen dialog demo.
///
/// In en, this message translates to:
/// **'Full Screen Dialog'**
String get dialogFullscreenTitle;
/// Save button for full screen dialog demo.
///
/// In en, this message translates to:
/// **'SAVE'**
String get dialogFullscreenSave;
/// Description for full screen dialog demo.
///
/// In en, this message translates to:
/// **'A full screen dialog demo'**
String get dialogFullscreenDescription;
/// Button text for a generic iOS-style button.
///
/// In en, this message translates to:
/// **'Button'**
String get cupertinoButton;
/// Button text for a iOS-style button with a filled background.
///
/// In en, this message translates to:
/// **'With Background'**
String get cupertinoButtonWithBackground;
/// iOS-style alert cancel option.
///
/// In en, this message translates to:
/// **'Cancel'**
String get cupertinoAlertCancel;
/// iOS-style alert discard option.
///
/// In en, this message translates to:
/// **'Discard'**
String get cupertinoAlertDiscard;
/// iOS-style alert title for location permission.
///
/// In en, this message translates to:
/// **'Allow \"Maps\" to access your location while you are using the app?'**
String get cupertinoAlertLocationTitle;
/// iOS-style alert description for location permission.
///
/// In en, this message translates to:
/// **'Your current location will be displayed on the map and used for directions, nearby search results, and estimated travel times.'**
String get cupertinoAlertLocationDescription;
/// iOS-style alert allow option.
///
/// In en, this message translates to:
/// **'Allow'**
String get cupertinoAlertAllow;
/// iOS-style alert don't allow option.
///
/// In en, this message translates to:
/// **'Don\'t Allow'**
String get cupertinoAlertDontAllow;
/// iOS-style alert title for selecting favorite dessert.
///
/// In en, this message translates to:
/// **'Select Favorite Dessert'**
String get cupertinoAlertFavoriteDessert;
/// iOS-style alert description for selecting favorite dessert.
///
/// In en, this message translates to:
/// **'Please select your favorite type of dessert from the list below. Your selection will be used to customize the suggested list of eateries in your area.'**
String get cupertinoAlertDessertDescription;
/// iOS-style alert cheesecake option.
///
/// In en, this message translates to:
/// **'Cheesecake'**
String get cupertinoAlertCheesecake;
/// iOS-style alert tiramisu option.
///
/// In en, this message translates to:
/// **'Tiramisu'**
String get cupertinoAlertTiramisu;
/// iOS-style alert apple pie option.
///
/// In en, this message translates to:
/// **'Apple Pie'**
String get cupertinoAlertApplePie;
/// iOS-style alert chocolate brownie option.
///
/// In en, this message translates to:
/// **'Chocolate Brownie'**
String get cupertinoAlertChocolateBrownie;
/// Button text to show iOS-style alert.
///
/// In en, this message translates to:
/// **'Show Alert'**
String get cupertinoShowAlert;
/// Tab title for the color red.
///
/// In en, this message translates to:
/// **'RED'**
String get colorsRed;
/// Tab title for the color pink.
///
/// In en, this message translates to:
/// **'PINK'**
String get colorsPink;
/// Tab title for the color purple.
///
/// In en, this message translates to:
/// **'PURPLE'**
String get colorsPurple;
/// Tab title for the color deep purple.
///
/// In en, this message translates to:
/// **'DEEP PURPLE'**
String get colorsDeepPurple;
/// Tab title for the color indigo.
///
/// In en, this message translates to:
/// **'INDIGO'**
String get colorsIndigo;
/// Tab title for the color blue.
///
/// In en, this message translates to:
/// **'BLUE'**
String get colorsBlue;
/// Tab title for the color light blue.
///
/// In en, this message translates to:
/// **'LIGHT BLUE'**
String get colorsLightBlue;
/// Tab title for the color cyan.
///
/// In en, this message translates to:
/// **'CYAN'**
String get colorsCyan;
/// Tab title for the color teal.
///
/// In en, this message translates to:
/// **'TEAL'**
String get colorsTeal;
/// Tab title for the color green.
///
/// In en, this message translates to:
/// **'GREEN'**
String get colorsGreen;
/// Tab title for the color light green.
///
/// In en, this message translates to:
/// **'LIGHT GREEN'**
String get colorsLightGreen;
/// Tab title for the color lime.
///
/// In en, this message translates to:
/// **'LIME'**
String get colorsLime;
/// Tab title for the color yellow.
///
/// In en, this message translates to:
/// **'YELLOW'**
String get colorsYellow;
/// Tab title for the color amber.
///
/// In en, this message translates to:
/// **'AMBER'**
String get colorsAmber;
/// Tab title for the color orange.
///
/// In en, this message translates to:
/// **'ORANGE'**
String get colorsOrange;
/// Tab title for the color deep orange.
///
/// In en, this message translates to:
/// **'DEEP ORANGE'**
String get colorsDeepOrange;
/// Tab title for the color brown.
///
/// In en, this message translates to:
/// **'BROWN'**
String get colorsBrown;
/// Tab title for the color grey.
///
/// In en, this message translates to:
/// **'GREY'**
String get colorsGrey;
/// Tab title for the color blue grey.
///
/// In en, this message translates to:
/// **'BLUE GREY'**
String get colorsBlueGrey;
/// Title for Chennai location.
///
/// In en, this message translates to:
/// **'Chennai'**
String get placeChennai;
/// Title for Tanjore location.
///
/// In en, this message translates to:
/// **'Tanjore'**
String get placeTanjore;
/// Title for Chettinad location.
///
/// In en, this message translates to:
/// **'Chettinad'**
String get placeChettinad;
/// Title for Pondicherry location.
///
/// In en, this message translates to:
/// **'Pondicherry'**
String get placePondicherry;
/// Title for Flower Market location.
///
/// In en, this message translates to:
/// **'Flower Market'**
String get placeFlowerMarket;
/// Title for Bronze Works location.
///
/// In en, this message translates to:
/// **'Bronze Works'**
String get placeBronzeWorks;
/// Title for Market location.
///
/// In en, this message translates to:
/// **'Market'**
String get placeMarket;
/// Title for Thanjavur Temple location.
///
/// In en, this message translates to:
/// **'Thanjavur Temple'**
String get placeThanjavurTemple;
/// Title for Salt Farm location.
///
/// In en, this message translates to:
/// **'Salt Farm'**
String get placeSaltFarm;
/// Title for image of people riding on scooters.
///
/// In en, this message translates to:
/// **'Scooters'**
String get placeScooters;
/// Title for an image of a silk maker.
///
/// In en, this message translates to:
/// **'Silk Maker'**
String get placeSilkMaker;
/// Title for an image of preparing lunch.
///
/// In en, this message translates to:
/// **'Lunch Prep'**
String get placeLunchPrep;
/// Title for Beach location.
///
/// In en, this message translates to:
/// **'Beach'**
String get placeBeach;
/// Title for an image of a fisherman.
///
/// In en, this message translates to:
/// **'Fisherman'**
String get placeFisherman;
/// The title and name for the starter app.
///
/// In en, this message translates to:
/// **'Starter app'**
String get starterAppTitle;
/// The description for the starter app.
///
/// In en, this message translates to:
/// **'A responsive starter layout'**
String get starterAppDescription;
/// Generic placeholder for button.
///
/// In en, this message translates to:
/// **'BUTTON'**
String get starterAppGenericButton;
/// Tooltip on add icon.
///
/// In en, this message translates to:
/// **'Add'**
String get starterAppTooltipAdd;
/// Tooltip on favorite icon.
///
/// In en, this message translates to:
/// **'Favorite'**
String get starterAppTooltipFavorite;
/// Tooltip on share icon.
///
/// In en, this message translates to:
/// **'Share'**
String get starterAppTooltipShare;
/// Tooltip on search icon.
///
/// In en, this message translates to:
/// **'Search'**
String get starterAppTooltipSearch;
/// Generic placeholder for title in app bar.
///
/// In en, this message translates to:
/// **'Title'**
String get starterAppGenericTitle;
/// Generic placeholder for subtitle in drawer.
///
/// In en, this message translates to:
/// **'Subtitle'**
String get starterAppGenericSubtitle;
/// Generic placeholder for headline in drawer.
///
/// In en, this message translates to:
/// **'Headline'**
String get starterAppGenericHeadline;
/// Generic placeholder for body text in drawer.
///
/// In en, this message translates to:
/// **'Body'**
String get starterAppGenericBody;
/// Generic placeholder drawer item.
///
/// In en, this message translates to:
/// **'Item {value}'**
String starterAppDrawerItem(Object value);
/// Caption for a menu page.
///
/// In en, this message translates to:
/// **'MENU'**
String get shrineMenuCaption;
/// A tab showing products from all categories.
///
/// In en, this message translates to:
/// **'ALL'**
String get shrineCategoryNameAll;
/// A category of products consisting of accessories (clothing items).
///
/// In en, this message translates to:
/// **'ACCESSORIES'**
String get shrineCategoryNameAccessories;
/// A category of products consisting of clothing.
///
/// In en, this message translates to:
/// **'CLOTHING'**
String get shrineCategoryNameClothing;
/// A category of products consisting of items used at home.
///
/// In en, this message translates to:
/// **'HOME'**
String get shrineCategoryNameHome;
/// Label for a logout button.
///
/// In en, this message translates to:
/// **'LOGOUT'**
String get shrineLogoutButtonCaption;
/// On the login screen, a label for a textfield for the user to input their username.
///
/// In en, this message translates to:
/// **'Username'**
String get shrineLoginUsernameLabel;
/// On the login screen, a label for a textfield for the user to input their password.
///
/// In en, this message translates to:
/// **'Password'**
String get shrineLoginPasswordLabel;
/// On the login screen, the caption for a button to cancel login.
///
/// In en, this message translates to:
/// **'CANCEL'**
String get shrineCancelButtonCaption;
/// On the login screen, the caption for a button to proceed login.
///
/// In en, this message translates to:
/// **'NEXT'**
String get shrineNextButtonCaption;
/// Caption for a shopping cart page.
///
/// In en, this message translates to:
/// **'CART'**
String get shrineCartPageCaption;
/// A text showing the number of items for a specific product.
///
/// In en, this message translates to:
/// **'Quantity: {quantity}'**
String shrineProductQuantity(Object quantity);
/// A text showing the unit price of each product. Used as: 'Quantity: 3 x $129'. The currency will be handled by the formatter.
///
/// In en, this message translates to:
/// **'x {price}'**
String shrineProductPrice(Object price);
/// A text showing the total number of items in the cart.
///
/// In en, this message translates to:
/// **'{quantity, plural, =0{NO ITEMS} =1{1 ITEM} other{{quantity} ITEMS}}'**
String shrineCartItemCount(num quantity);
/// Caption for a button used to clear the cart.
///
/// In en, this message translates to:
/// **'CLEAR CART'**
String get shrineCartClearButtonCaption;
/// Label for a text showing total price of the items in the cart.
///
/// In en, this message translates to:
/// **'TOTAL'**
String get shrineCartTotalCaption;
/// Label for a text showing the subtotal price of the items in the cart (excluding shipping and tax).
///
/// In en, this message translates to:
/// **'Subtotal:'**
String get shrineCartSubtotalCaption;
/// Label for a text showing the shipping cost for the items in the cart.
///
/// In en, this message translates to:
/// **'Shipping:'**
String get shrineCartShippingCaption;
/// Label for a text showing the tax for the items in the cart.
///
/// In en, this message translates to:
/// **'Tax:'**
String get shrineCartTaxCaption;
/// Name of the product 'Vagabond sack'.
///
/// In en, this message translates to:
/// **'Vagabond sack'**
String get shrineProductVagabondSack;
/// Name of the product 'Stella sunglasses'.
///
/// In en, this message translates to:
/// **'Stella sunglasses'**
String get shrineProductStellaSunglasses;
/// Name of the product 'Whitney belt'.
///
/// In en, this message translates to:
/// **'Whitney belt'**
String get shrineProductWhitneyBelt;
/// Name of the product 'Garden strand'.
///
/// In en, this message translates to:
/// **'Garden strand'**
String get shrineProductGardenStrand;
/// Name of the product 'Strut earrings'.
///
/// In en, this message translates to:
/// **'Strut earrings'**
String get shrineProductStrutEarrings;
/// Name of the product 'Varsity socks'.
///
/// In en, this message translates to:
/// **'Varsity socks'**
String get shrineProductVarsitySocks;
/// Name of the product 'Weave keyring'.
///
/// In en, this message translates to:
/// **'Weave keyring'**
String get shrineProductWeaveKeyring;
/// Name of the product 'Gatsby hat'.
///
/// In en, this message translates to:
/// **'Gatsby hat'**
String get shrineProductGatsbyHat;
/// Name of the product 'Shrug bag'.
///
/// In en, this message translates to:
/// **'Shrug bag'**
String get shrineProductShrugBag;
/// Name of the product 'Gilt desk trio'.
///
/// In en, this message translates to:
/// **'Gilt desk trio'**
String get shrineProductGiltDeskTrio;
/// Name of the product 'Copper wire rack'.
///
/// In en, this message translates to:
/// **'Copper wire rack'**
String get shrineProductCopperWireRack;
/// Name of the product 'Soothe ceramic set'.
///
/// In en, this message translates to:
/// **'Soothe ceramic set'**
String get shrineProductSootheCeramicSet;
/// Name of the product 'Hurrahs tea set'.
///
/// In en, this message translates to:
/// **'Hurrahs tea set'**
String get shrineProductHurrahsTeaSet;
/// Name of the product 'Blue stone mug'.
///
/// In en, this message translates to:
/// **'Blue stone mug'**
String get shrineProductBlueStoneMug;
/// Name of the product 'Rainwater tray'.
///
/// In en, this message translates to:
/// **'Rainwater tray'**
String get shrineProductRainwaterTray;
/// Name of the product 'Chambray napkins'.
///
/// In en, this message translates to:
/// **'Chambray napkins'**
String get shrineProductChambrayNapkins;
/// Name of the product 'Succulent planters'.
///
/// In en, this message translates to:
/// **'Succulent planters'**
String get shrineProductSucculentPlanters;
/// Name of the product 'Quartet table'.
///
/// In en, this message translates to:
/// **'Quartet table'**
String get shrineProductQuartetTable;
/// Name of the product 'Kitchen quattro'.
///
/// In en, this message translates to:
/// **'Kitchen quattro'**
String get shrineProductKitchenQuattro;
/// Name of the product 'Clay sweater'.
///
/// In en, this message translates to:
/// **'Clay sweater'**
String get shrineProductClaySweater;
/// Name of the product 'Sea tunic'.
///
/// In en, this message translates to:
/// **'Sea tunic'**
String get shrineProductSeaTunic;
/// Name of the product 'Plaster tunic'.
///
/// In en, this message translates to:
/// **'Plaster tunic'**
String get shrineProductPlasterTunic;
/// Name of the product 'White pinstripe shirt'.
///
/// In en, this message translates to:
/// **'White pinstripe shirt'**
String get shrineProductWhitePinstripeShirt;
/// Name of the product 'Chambray shirt'.
///
/// In en, this message translates to:
/// **'Chambray shirt'**
String get shrineProductChambrayShirt;
/// Name of the product 'Seabreeze sweater'.
///
/// In en, this message translates to:
/// **'Seabreeze sweater'**
String get shrineProductSeabreezeSweater;
/// Name of the product 'Gentry jacket'.
///
/// In en, this message translates to:
/// **'Gentry jacket'**
String get shrineProductGentryJacket;
/// Name of the product 'Navy trousers'.
///
/// In en, this message translates to:
/// **'Navy trousers'**
String get shrineProductNavyTrousers;
/// Name of the product 'Walter henley (white)'.
///
/// In en, this message translates to:
/// **'Walter henley (white)'**
String get shrineProductWalterHenleyWhite;
/// Name of the product 'Surf and perf shirt'.
///
/// In en, this message translates to:
/// **'Surf and perf shirt'**
String get shrineProductSurfAndPerfShirt;
/// Name of the product 'Ginger scarf'.
///
/// In en, this message translates to:
/// **'Ginger scarf'**
String get shrineProductGingerScarf;
/// Name of the product 'Ramona crossover'.
///
/// In en, this message translates to:
/// **'Ramona crossover'**
String get shrineProductRamonaCrossover;
/// Name of the product 'Classic white collar'.
///
/// In en, this message translates to:
/// **'Classic white collar'**
String get shrineProductClassicWhiteCollar;
/// Name of the product 'Cerise scallop tee'.
///
/// In en, this message translates to:
/// **'Cerise scallop tee'**
String get shrineProductCeriseScallopTee;
/// Name of the product 'Shoulder rolls tee'.
///
/// In en, this message translates to:
/// **'Shoulder rolls tee'**
String get shrineProductShoulderRollsTee;
/// Name of the product 'Grey slouch tank'.
///
/// In en, this message translates to:
/// **'Grey slouch tank'**
String get shrineProductGreySlouchTank;
/// Name of the product 'Sunshirt dress'.
///
/// In en, this message translates to:
/// **'Sunshirt dress'**
String get shrineProductSunshirtDress;
/// Name of the product 'Fine lines tee'.
///
/// In en, this message translates to:
/// **'Fine lines tee'**
String get shrineProductFineLinesTee;
/// The tooltip text for a search button. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'Search'**
String get shrineTooltipSearch;
/// The tooltip text for a settings button. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'Settings'**
String get shrineTooltipSettings;
/// The tooltip text for a menu button. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'Open menu'**
String get shrineTooltipOpenMenu;
/// The tooltip text for a button to close a menu. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'Close menu'**
String get shrineTooltipCloseMenu;
/// The tooltip text for a button to close the shopping cart page. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'Close cart'**
String get shrineTooltipCloseCart;
/// The description of a shopping cart button containing some products. Used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'{quantity, plural, =0{Shopping cart, no items} =1{Shopping cart, 1 item} other{Shopping cart, {quantity} items}}'**
String shrineScreenReaderCart(num quantity);
/// An announcement made by screen readers, such as TalkBack and VoiceOver to indicate the action of a button for adding a product to the cart.
///
/// In en, this message translates to:
/// **'Add to cart'**
String get shrineScreenReaderProductAddToCart;
/// A tooltip for a button to remove a product. This will be read by screen readers, such as TalkBack and VoiceOver when a product is added to the shopping cart.
///
/// In en, this message translates to:
/// **'Remove {product}'**
String shrineScreenReaderRemoveProductButton(Object product);
/// The tooltip text for a button to remove an item (a product) in a shopping cart. Also used as a semantic label, used by screen readers, such as TalkBack and VoiceOver.
///
/// In en, this message translates to:
/// **'Remove item'**
String get shrineTooltipRemoveItem;
/// Form field label to enter the number of diners.
///
/// In en, this message translates to:
/// **'Diners'**
String get craneFormDiners;
/// Form field label to select a date.
///
/// In en, this message translates to:
/// **'Select Date'**
String get craneFormDate;
/// Form field label to select a time.
///
/// In en, this message translates to:
/// **'Select Time'**
String get craneFormTime;
/// Form field label to select a location.
///
/// In en, this message translates to:
/// **'Select Location'**
String get craneFormLocation;
/// Form field label to select the number of travellers.
///
/// In en, this message translates to:
/// **'Travelers'**
String get craneFormTravelers;
/// Form field label to choose a travel origin.
///
/// In en, this message translates to:
/// **'Choose Origin'**
String get craneFormOrigin;
/// Form field label to choose a travel destination.
///
/// In en, this message translates to:
/// **'Choose Destination'**
String get craneFormDestination;
/// Form field label to select multiple dates.
///
/// In en, this message translates to:
/// **'Select Dates'**
String get craneFormDates;
/// Generic text for an amount of hours, abbreviated to the shortest form. For example 1h. {hours} should remain untranslated.
///
/// In en, this message translates to:
/// **'{hours, plural, =1{1h} other{{hours}h}}'**
String craneHours(num hours);
/// Generic text for an amount of minutes, abbreviated to the shortest form. For example 15m. {minutes} should remain untranslated.
///
/// In en, this message translates to:
/// **'{minutes, plural, =1{1m} other{{minutes}m}}'**
String craneMinutes(num minutes);
/// A pattern to define the layout of a flight duration string. For example in English one might say 1h 15m. Translation should only rearrange the inputs. {hoursShortForm} would for example be replaced by 1h, already translated to the given locale. {minutesShortForm} would for example be replaced by 15m, already translated to the given locale.
///
/// In en, this message translates to:
/// **'{hoursShortForm} {minutesShortForm}'**
String craneFlightDuration(Object hoursShortForm, Object minutesShortForm);
/// Title for FLY tab.
///
/// In en, this message translates to:
/// **'FLY'**
String get craneFly;
/// Title for SLEEP tab.
///
/// In en, this message translates to:
/// **'SLEEP'**
String get craneSleep;
/// Title for EAT tab.
///
/// In en, this message translates to:
/// **'EAT'**
String get craneEat;
/// Subhead for FLY tab.
///
/// In en, this message translates to:
/// **'Explore Flights by Destination'**
String get craneFlySubhead;
/// Subhead for SLEEP tab.
///
/// In en, this message translates to:
/// **'Explore Properties by Destination'**
String get craneSleepSubhead;
/// Subhead for EAT tab.
///
/// In en, this message translates to:
/// **'Explore Restaurants by Destination'**
String get craneEatSubhead;
/// Label indicating if a flight is nonstop or how many layovers it includes.
///
/// In en, this message translates to:
/// **'{numberOfStops, plural, =0{Nonstop} =1{1 stop} other{{numberOfStops} stops}}'**
String craneFlyStops(num numberOfStops);
/// Text indicating the number of available properties (temporary rentals). Always plural.
///
/// In en, this message translates to:
/// **'{totalProperties, plural, =0{No Available Properties} =1{1 Available Properties} other{{totalProperties} Available Properties}}'**
String craneSleepProperties(num totalProperties);
/// Text indicating the number of restaurants. Always plural.
///
/// In en, this message translates to:
/// **'{totalRestaurants, plural, =0{No Restaurants} =1{1 Restaurant} other{{totalRestaurants} Restaurants}}'**
String craneEatRestaurants(num totalRestaurants);
/// Label for city.
///
/// In en, this message translates to:
/// **'Aspen, United States'**
String get craneFly0;
/// Label for city.
///
/// In en, this message translates to:
/// **'Big Sur, United States'**
String get craneFly1;
/// Label for city.
///
/// In en, this message translates to:
/// **'Khumbu Valley, Nepal'**
String get craneFly2;
/// Label for city.
///
/// In en, this message translates to:
/// **'Machu Picchu, Peru'**
String get craneFly3;
/// Label for city.
///
/// In en, this message translates to:
/// **'Malé, Maldives'**
String get craneFly4;
/// Label for city.
///
/// In en, this message translates to:
/// **'Vitznau, Switzerland'**
String get craneFly5;
/// Label for city.
///
/// In en, this message translates to:
/// **'Mexico City, Mexico'**
String get craneFly6;
/// Label for city.
///
/// In en, this message translates to:
/// **'Mount Rushmore, United States'**
String get craneFly7;
/// Label for city.
///
/// In en, this message translates to:
/// **'Singapore'**
String get craneFly8;
/// Label for city.
///
/// In en, this message translates to:
/// **'Havana, Cuba'**
String get craneFly9;
/// Label for city.
///
/// In en, this message translates to:
/// **'Cairo, Egypt'**
String get craneFly10;
/// Label for city.
///
/// In en, this message translates to:
/// **'Lisbon, Portugal'**
String get craneFly11;
/// Label for city.
///
/// In en, this message translates to:
/// **'Napa, United States'**
String get craneFly12;
/// Label for city.
///
/// In en, this message translates to:
/// **'Bali, Indonesia'**
String get craneFly13;
/// Label for city.
///
/// In en, this message translates to:
/// **'Malé, Maldives'**
String get craneSleep0;
/// Label for city.
///
/// In en, this message translates to:
/// **'Aspen, United States'**
String get craneSleep1;
/// Label for city.
///
/// In en, this message translates to:
/// **'Machu Picchu, Peru'**
String get craneSleep2;
/// Label for city.
///
/// In en, this message translates to:
/// **'Havana, Cuba'**
String get craneSleep3;
/// Label for city.
///
/// In en, this message translates to:
/// **'Vitznau, Switzerland'**
String get craneSleep4;
/// Label for city.
///
/// In en, this message translates to:
/// **'Big Sur, United States'**
String get craneSleep5;
/// Label for city.
///
/// In en, this message translates to:
/// **'Napa, United States'**
String get craneSleep6;
/// Label for city.
///
/// In en, this message translates to:
/// **'Porto, Portugal'**
String get craneSleep7;
/// Label for city.
///
/// In en, this message translates to:
/// **'Tulum, Mexico'**
String get craneSleep8;
/// Label for city.
///
/// In en, this message translates to:
/// **'Lisbon, Portugal'**
String get craneSleep9;
/// Label for city.
///
/// In en, this message translates to:
/// **'Cairo, Egypt'**
String get craneSleep10;
/// Label for city.
///
/// In en, this message translates to:
/// **'Taipei, Taiwan'**
String get craneSleep11;
/// Label for city.
///
/// In en, this message translates to:
/// **'Naples, Italy'**
String get craneEat0;
/// Label for city.
///
/// In en, this message translates to:
/// **'Dallas, United States'**
String get craneEat1;
/// Label for city.
///
/// In en, this message translates to:
/// **'Córdoba, Argentina'**
String get craneEat2;
/// Label for city.
///
/// In en, this message translates to:
/// **'Portland, United States'**
String get craneEat3;
/// Label for city.
///
/// In en, this message translates to:
/// **'Paris, France'**
String get craneEat4;
/// Label for city.
///
/// In en, this message translates to:
/// **'Seoul, South Korea'**
String get craneEat5;
/// Label for city.
///
/// In en, this message translates to:
/// **'Seattle, United States'**
String get craneEat6;
/// Label for city.
///
/// In en, this message translates to:
/// **'Nashville, United States'**
String get craneEat7;
/// Label for city.
///
/// In en, this message translates to:
/// **'Atlanta, United States'**
String get craneEat8;
/// Label for city.
///
/// In en, this message translates to:
/// **'Madrid, Spain'**
String get craneEat9;
/// Label for city.
///
/// In en, this message translates to:
/// **'Lisbon, Portugal'**
String get craneEat10;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Chalet in a snowy landscape with evergreen trees'**
String get craneFly0SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Tent in a field'**
String get craneFly1SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Prayer flags in front of snowy mountain'**
String get craneFly2SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Machu Picchu citadel'**
String get craneFly3SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Overwater bungalows'**
String get craneFly4SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Lake-side hotel in front of mountains'**
String get craneFly5SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Aerial view of Palacio de Bellas Artes'**
String get craneFly6SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Mount Rushmore'**
String get craneFly7SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Supertree Grove'**
String get craneFly8SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Man leaning on an antique blue car'**
String get craneFly9SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Al-Azhar Mosque towers during sunset'**
String get craneFly10SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Brick lighthouse at sea'**
String get craneFly11SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Pool with palm trees'**
String get craneFly12SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Sea-side pool with palm trees'**
String get craneFly13SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Overwater bungalows'**
String get craneSleep0SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Chalet in a snowy landscape with evergreen trees'**
String get craneSleep1SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Machu Picchu citadel'**
String get craneSleep2SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Man leaning on an antique blue car'**
String get craneSleep3SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Lake-side hotel in front of mountains'**
String get craneSleep4SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Tent in a field'**
String get craneSleep5SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Pool with palm trees'**
String get craneSleep6SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Colorful apartments at Riberia Square'**
String get craneSleep7SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Mayan ruins on a cliff above a beach'**
String get craneSleep8SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Brick lighthouse at sea'**
String get craneSleep9SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Al-Azhar Mosque towers during sunset'**
String get craneSleep10SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Taipei 101 skyscraper'**
String get craneSleep11SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Pizza in a wood-fired oven'**
String get craneEat0SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Empty bar with diner-style stools'**
String get craneEat1SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Burger'**
String get craneEat2SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Korean taco'**
String get craneEat3SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Chocolate dessert'**
String get craneEat4SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Artsy restaurant seating area'**
String get craneEat5SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Shrimp dish'**
String get craneEat6SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Bakery entrance'**
String get craneEat7SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Plate of crawfish'**
String get craneEat8SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Cafe counter with pastries'**
String get craneEat9SemanticLabel;
/// Semantic label for an image.
///
/// In en, this message translates to:
/// **'Woman holding huge pastrami sandwich'**
String get craneEat10SemanticLabel;
/// Menu item for the front page of the news app.
///
/// In en, this message translates to:
/// **'Front Page'**
String get fortnightlyMenuFrontPage;
/// Menu item for the world news section of the news app.
///
/// In en, this message translates to:
/// **'World'**
String get fortnightlyMenuWorld;
/// Menu item for the United States news section of the news app.
///
/// In en, this message translates to:
/// **'US'**
String get fortnightlyMenuUS;
/// Menu item for the political news section of the news app.
///
/// In en, this message translates to:
/// **'Politics'**
String get fortnightlyMenuPolitics;
/// Menu item for the business news section of the news app.
///
/// In en, this message translates to:
/// **'Business'**
String get fortnightlyMenuBusiness;
/// Menu item for the tech news section of the news app.
///
/// In en, this message translates to:
/// **'Tech'**
String get fortnightlyMenuTech;
/// Menu item for the science news section of the news app.
///
/// In en, this message translates to:
/// **'Science'**
String get fortnightlyMenuScience;
/// Menu item for the sports news section of the news app.
///
/// In en, this message translates to:
/// **'Sports'**
String get fortnightlyMenuSports;
/// Menu item for the travel news section of the news app.
///
/// In en, this message translates to:
/// **'Travel'**
String get fortnightlyMenuTravel;
/// Menu item for the culture news section of the news app.
///
/// In en, this message translates to:
/// **'Culture'**
String get fortnightlyMenuCulture;
/// Hashtag for the tech design trending topic of the news app.
///
/// In en, this message translates to:
/// **'TechDesign'**
String get fortnightlyTrendingTechDesign;
/// Hashtag for the reform trending topic of the news app.
///
/// In en, this message translates to:
/// **'Reform'**
String get fortnightlyTrendingReform;
/// Hashtag for the healthcare revolution trending topic of the news app.
///
/// In en, this message translates to:
/// **'HealthcareRevolution'**
String get fortnightlyTrendingHealthcareRevolution;
/// Hashtag for the green army trending topic of the news app.
///
/// In en, this message translates to:
/// **'GreenArmy'**
String get fortnightlyTrendingGreenArmy;
/// Hashtag for the stocks trending topic of the news app.
///
/// In en, this message translates to:
/// **'Stocks'**
String get fortnightlyTrendingStocks;
/// Title for news section regarding the latest updates.
///
/// In en, this message translates to:
/// **'Latest Updates'**
String get fortnightlyLatestUpdates;
/// Headline for a news article about healthcare.
///
/// In en, this message translates to:
/// **'The Quiet, Yet Powerful Healthcare Revolution'**
String get fortnightlyHeadlineHealthcare;
/// Headline for a news article about war.
///
/// In en, this message translates to:
/// **'Divided American Lives During War'**
String get fortnightlyHeadlineWar;
/// Headline for a news article about gasoline.
///
/// In en, this message translates to:
/// **'The Future of Gasoline'**
String get fortnightlyHeadlineGasoline;
/// Headline for a news article about the green army.
///
/// In en, this message translates to:
/// **'Reforming The Green Army From Within'**
String get fortnightlyHeadlineArmy;
/// Headline for a news article about stocks.
///
/// In en, this message translates to:
/// **'As Stocks Stagnate, Many Look To Currency'**
String get fortnightlyHeadlineStocks;
/// Headline for a news article about fabric.
///
/// In en, this message translates to:
/// **'Designers Use Tech To Make Futuristic Fabrics'**
String get fortnightlyHeadlineFabrics;
/// Headline for a news article about feminists and partisanship.
///
/// In en, this message translates to:
/// **'Feminists Take On Partisanship'**
String get fortnightlyHeadlineFeminists;
/// Headline for a news article about bees.
///
/// In en, this message translates to:
/// **'Farmland Bees In Short Supply'**
String get fortnightlyHeadlineBees;
/// Text label for Inbox destination.
///
/// In en, this message translates to:
/// **'Inbox'**
String get replyInboxLabel;
/// Text label for Starred destination.
///
/// In en, this message translates to:
/// **'Starred'**
String get replyStarredLabel;
/// Text label for Sent destination.
///
/// In en, this message translates to:
/// **'Sent'**
String get replySentLabel;
/// Text label for Trash destination.
///
/// In en, this message translates to:
/// **'Trash'**
String get replyTrashLabel;
/// Text label for Spam destination.
///
/// In en, this message translates to:
/// **'Spam'**
String get replySpamLabel;
/// Text label for Drafts destination.
///
/// In en, this message translates to:
/// **'Drafts'**
String get replyDraftsLabel;
/// Option title for TwoPane demo on foldable devices.
///
/// In en, this message translates to:
/// **'Foldable'**
String get demoTwoPaneFoldableLabel;
/// Description for the foldable option configuration on the TwoPane demo.
///
/// In en, this message translates to:
/// **'This is how TwoPane behaves on a foldable device.'**
String get demoTwoPaneFoldableDescription;
/// Option title for TwoPane demo in small screen mode. Counterpart of the foldable option.
///
/// In en, this message translates to:
/// **'Small Screen'**
String get demoTwoPaneSmallScreenLabel;
/// Description for the small screen option configuration on the TwoPane demo.
///
/// In en, this message translates to:
/// **'This is how TwoPane behaves on a small screen device.'**
String get demoTwoPaneSmallScreenDescription;
/// Option title for TwoPane demo in tablet or desktop mode.
///
/// In en, this message translates to:
/// **'Tablet / Desktop'**
String get demoTwoPaneTabletLabel;
/// Description for the tablet / desktop option configuration on the TwoPane demo.
///
/// In en, this message translates to:
/// **'This is how TwoPane behaves on a larger screen like a tablet or desktop.'**
String get demoTwoPaneTabletDescription;
/// Title for the TwoPane widget demo.
///
/// In en, this message translates to:
/// **'TwoPane'**
String get demoTwoPaneTitle;
/// Subtitle for the TwoPane widget demo.
///
/// In en, this message translates to:
/// **'Responsive layouts on foldable, large, and small screens'**
String get demoTwoPaneSubtitle;
/// Tip for user, visible on the right side of the splash screen when Gallery runs on a foldable device.
///
/// In en, this message translates to:
/// **'Select a demo'**
String get splashSelectDemo;
/// Title of one of the panes in the TwoPane demo. It sits on top of a list of items.
///
/// In en, this message translates to:
/// **'List'**
String get demoTwoPaneList;
/// Title of one of the panes in the TwoPane demo, which shows details of the currently selected item.
///
/// In en, this message translates to:
/// **'Details'**
String get demoTwoPaneDetails;
/// Tip for user, visible on the right side of the TwoPane widget demo in the foldable configuration.
///
/// In en, this message translates to:
/// **'Select an item'**
String get demoTwoPaneSelectItem;
/// Generic item placeholder visible in the TwoPane widget demo.
///
/// In en, this message translates to:
/// **'Item {value}'**
String demoTwoPaneItem(Object value);
/// Generic item description or details visible in the TwoPane widget demo.
///
/// In en, this message translates to:
/// **'Item {value} details'**
String demoTwoPaneItemDetails(Object value);
}
class _GalleryLocalizationsDelegate extends LocalizationsDelegate<GalleryLocalizations> {
const _GalleryLocalizationsDelegate();
@override
Future<GalleryLocalizations> load(Locale locale) {
return SynchronousFuture<GalleryLocalizations>(lookupGalleryLocalizations(locale));
}
@override
bool isSupported(Locale locale) => <String>['en'].contains(locale.languageCode);
@override
bool shouldReload(_GalleryLocalizationsDelegate old) => false;
}
GalleryLocalizations lookupGalleryLocalizations(Locale locale) {
// Lookup logic when language+country codes are specified.
switch (locale.languageCode) {
case 'en': {
switch (locale.countryCode) {
case 'IS': return GalleryLocalizationsEnIs();
}
break;
}
}
// Lookup logic when only language code is specified.
switch (locale.languageCode) {
case 'en': return GalleryLocalizationsEn();
}
throw FlutterError(
'GalleryLocalizations.delegate failed to load unsupported locale "$locale". This is likely '
'an issue with the localizations generation tool. Please file an issue '
'on GitHub with a reproducible sample app and the gen-l10n configuration '
'that was used.'
);
}
| flutter/dev/integration_tests/new_gallery/lib/gallery_localizations.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/gallery_localizations.dart",
"repo_id": "flutter",
"token_count": 42105
} | 536 |
// Copyright 2014 The Flutter 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';
import 'metrics.dart';
class SettingsIcon extends StatelessWidget {
const SettingsIcon(this.time, {super.key});
final double time;
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: _SettingsIconPainter(time: time, context: context),
);
}
}
class _SettingsIconPainter extends CustomPainter {
_SettingsIconPainter({required this.time, required this.context});
final double time;
final BuildContext context;
late Offset _center;
late double _scaling;
late Canvas _canvas;
/// Computes [_center] and [_scaling], parameters used to convert offsets
/// and lengths in relative units into logical pixels.
///
/// The icon is aligned to the bottom-start corner.
void _computeCenterAndScaling(Size size) {
_scaling = min(size.width / unitWidth, size.height / unitHeight);
_center = Directionality.of(context) == TextDirection.ltr
? Offset(
unitWidth * _scaling / 2, size.height - unitHeight * _scaling / 2)
: Offset(size.width - unitWidth * _scaling / 2,
size.height - unitHeight * _scaling / 2);
}
/// Transforms an offset in relative units into an offset in logical pixels.
Offset _transform(Offset offset) {
return _center + offset * _scaling;
}
/// Transforms a length in relative units into a dimension in logical pixels.
double _size(double length) {
return length * _scaling;
}
/// A rectangle with a fixed location, used to locate gradients.
Rect get _fixedRect {
final Offset topLeft = Offset(-_size(stickLength / 2), -_size(stickWidth / 2));
final Offset bottomRight = Offset(_size(stickLength / 2), _size(stickWidth / 2));
return Rect.fromPoints(topLeft, bottomRight);
}
/// Black or white paint, depending on brightness.
Paint get _monoPaint {
final Color monoColor =
Theme.of(context).colorScheme.brightness == Brightness.light
? Colors.black
: Colors.white;
return Paint()..color = monoColor;
}
/// Pink paint with horizontal gradient.
Paint get _pinkPaint {
const LinearGradient shader = LinearGradient(colors: <Color>[pinkLeft, pinkRight]);
final Rect shaderRect = _fixedRect.translate(
_size(-(stickLength - colorLength(time)) / 2),
0,
);
return Paint()..shader = shader.createShader(shaderRect);
}
/// Teal paint with horizontal gradient.
Paint get _tealPaint {
const LinearGradient shader = LinearGradient(colors: <Color>[tealLeft, tealRight]);
final Rect shaderRect = _fixedRect.translate(
_size((stickLength - colorLength(time)) / 2),
0,
);
return Paint()..shader = shader.createShader(shaderRect);
}
/// Paints a stadium-shaped stick.
void _paintStick({
required Offset center,
required double length,
required double width,
double angle = 0,
required Paint paint,
}) {
// Convert to pixels.
center = _transform(center);
length = _size(length);
width = _size(width);
// Paint.
width = min(width, length);
final double stretch = length / 2;
final double radius = width / 2;
_canvas.save();
_canvas.translate(center.dx, center.dy);
_canvas.rotate(angle);
final Rect leftOval = Rect.fromCircle(
center: Offset(-stretch + radius, 0),
radius: radius,
);
final Rect rightOval = Rect.fromCircle(
center: Offset(stretch - radius, 0),
radius: radius,
);
_canvas.drawPath(
Path()
..arcTo(leftOval, pi / 2, pi, false)
..arcTo(rightOval, -pi / 2, pi, false),
paint,
);
_canvas.restore();
}
@override
void paint(Canvas canvas, Size size) {
_computeCenterAndScaling(size);
_canvas = canvas;
if (isTransitionPhase(time)) {
_paintStick(
center: upperColorOffset(time),
length: colorLength(time),
width: stickWidth,
paint: _pinkPaint,
);
_paintStick(
center: lowerColorOffset(time),
length: colorLength(time),
width: stickWidth,
paint: _tealPaint,
);
_paintStick(
center: upperMonoOffset(time),
length: monoLength(time),
width: knobDiameter,
paint: _monoPaint,
);
_paintStick(
center: lowerMonoOffset(time),
length: monoLength(time),
width: knobDiameter,
paint: _monoPaint,
);
} else {
_paintStick(
center: upperKnobCenter,
length: stickLength,
width: knobDiameter,
angle: -knobRotation(time),
paint: _monoPaint,
);
_paintStick(
center: knobCenter(time),
length: stickLength,
width: knobDiameter,
angle: knobRotation(time),
paint: _monoPaint,
);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) =>
oldDelegate is! _SettingsIconPainter || oldDelegate.time != time;
}
| flutter/dev/integration_tests/new_gallery/lib/pages/settings_icon/icon.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/settings_icon/icon.dart",
"repo_id": "flutter",
"token_count": 1982
} | 537 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../../gallery_localizations.dart';
// Duration of time (e.g. 16h 12m)
String formattedDuration(BuildContext context, Duration duration,
{bool? abbreviated}) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
final String hoursShortForm = localizations.craneHours(duration.inHours);
final String minutesShortForm = localizations.craneMinutes(duration.inMinutes % 60);
return localizations.craneFlightDuration(hoursShortForm, minutesShortForm);
}
| flutter/dev/integration_tests/new_gallery/lib/studies/crane/model/formatters.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/model/formatters.dart",
"repo_id": "flutter",
"token_count": 191
} | 538 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../data/gallery_options.dart';
import '../../gallery_localizations.dart';
import '../../layout/adaptive.dart';
import '../../layout/image_placeholder.dart';
import '../../layout/text_scale.dart';
import 'app.dart';
import 'colors.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> with RestorationMixin {
final RestorableTextEditingController _usernameController =
RestorableTextEditingController();
final RestorableTextEditingController _passwordController =
RestorableTextEditingController();
@override
String get restorationId => 'login_page';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_usernameController, restorationId);
registerForRestoration(_passwordController, restorationId);
}
@override
Widget build(BuildContext context) {
return ApplyTextOptions(
child: Scaffold(
body: SafeArea(
child: _MainView(
usernameController: _usernameController.value,
passwordController: _passwordController.value,
),
),
),
);
}
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
super.dispose();
}
}
class _MainView extends StatelessWidget {
const _MainView({
this.usernameController,
this.passwordController,
});
final TextEditingController? usernameController;
final TextEditingController? passwordController;
void _login(BuildContext context) {
Navigator.of(context).restorablePushNamed(RallyApp.homeRoute);
}
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
List<Widget> listViewChildren;
if (isDesktop) {
final double desktopMaxWidth = 400.0 + 100.0 * (cappedTextScale(context) - 1);
listViewChildren = <Widget>[
_UsernameInput(
maxWidth: desktopMaxWidth,
usernameController: usernameController,
),
const SizedBox(height: 12),
_PasswordInput(
maxWidth: desktopMaxWidth,
passwordController: passwordController,
),
_LoginButton(
maxWidth: desktopMaxWidth,
onTap: () {
_login(context);
},
),
];
} else {
listViewChildren = <Widget>[
const _SmallLogo(),
_UsernameInput(
usernameController: usernameController,
),
const SizedBox(height: 12),
_PasswordInput(
passwordController: passwordController,
),
_ThumbButton(
onTap: () {
_login(context);
},
),
];
}
return Column(
children: <Widget>[
if (isDesktop) const _TopBar(),
Expanded(
child: Align(
alignment: isDesktop ? Alignment.center : Alignment.topCenter,
child: ListView(
restorationId: 'login_list_view',
shrinkWrap: true,
padding: const EdgeInsets.symmetric(horizontal: 24),
children: listViewChildren,
),
),
),
],
);
}
}
class _TopBar extends StatelessWidget {
const _TopBar();
@override
Widget build(BuildContext context) {
const SizedBox spacing = SizedBox(width: 30);
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return Container(
width: double.infinity,
margin: const EdgeInsets.only(top: 8),
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ExcludeSemantics(
child: SizedBox(
height: 80,
child: FadeInImagePlaceholder(
image:
const AssetImage('logo.png', package: 'rally_assets'),
placeholder: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
return SizedBox(
width: constraints.maxHeight,
height: constraints.maxHeight,
);
}),
),
),
),
spacing,
Text(
localizations.rallyLoginLoginToRally,
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
fontSize: 35 / reducedTextScale(context),
fontWeight: FontWeight.w600,
),
),
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
localizations.rallyLoginNoAccount,
style: Theme.of(context).textTheme.titleMedium,
),
spacing,
_BorderButton(
text: localizations.rallyLoginSignUp,
),
],
),
],
),
);
}
}
class _SmallLogo extends StatelessWidget {
const _SmallLogo();
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 64),
child: SizedBox(
height: 160,
child: ExcludeSemantics(
child: FadeInImagePlaceholder(
image: AssetImage('logo.png', package: 'rally_assets'),
placeholder: SizedBox.shrink(),
),
),
),
);
}
}
class _UsernameInput extends StatelessWidget {
const _UsernameInput({
this.maxWidth,
this.usernameController,
});
final double? maxWidth;
final TextEditingController? usernameController;
@override
Widget build(BuildContext context) {
return Align(
child: Container(
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
child: TextField(
autofillHints: const <String>[AutofillHints.username],
textInputAction: TextInputAction.next,
controller: usernameController,
decoration: InputDecoration(
labelText: GalleryLocalizations.of(context)!.rallyLoginUsername,
),
),
),
);
}
}
class _PasswordInput extends StatelessWidget {
const _PasswordInput({
this.maxWidth,
this.passwordController,
});
final double? maxWidth;
final TextEditingController? passwordController;
@override
Widget build(BuildContext context) {
return Align(
child: Container(
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
child: TextField(
controller: passwordController,
decoration: InputDecoration(
labelText: GalleryLocalizations.of(context)!.rallyLoginPassword,
),
obscureText: true,
),
),
);
}
}
class _ThumbButton extends StatefulWidget {
const _ThumbButton({
required this.onTap,
});
final VoidCallback onTap;
@override
_ThumbButtonState createState() => _ThumbButtonState();
}
class _ThumbButtonState extends State<_ThumbButton> {
BoxDecoration? borderDecoration;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
enabled: true,
label: GalleryLocalizations.of(context)!.rallyLoginLabelLogin,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: widget.onTap,
child: Focus(
onKeyEvent: (FocusNode node, KeyEvent event) {
if (event is KeyDownEvent || event is KeyRepeatEvent) {
if (event.logicalKey == LogicalKeyboardKey.enter ||
event.logicalKey == LogicalKeyboardKey.space) {
widget.onTap();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
onFocusChange: (bool hasFocus) {
if (hasFocus) {
setState(() {
borderDecoration = BoxDecoration(
border: Border.all(
color: Colors.white.withOpacity(0.5),
width: 2,
),
);
});
} else {
setState(() {
borderDecoration = null;
});
}
},
child: Container(
decoration: borderDecoration,
height: 120,
child: ExcludeSemantics(
child: Image.asset(
'thumb.png',
package: 'rally_assets',
),
),
),
),
),
),
);
}
}
class _LoginButton extends StatelessWidget {
const _LoginButton({
required this.onTap,
this.maxWidth,
});
final double? maxWidth;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Align(
child: Container(
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
padding: const EdgeInsets.symmetric(vertical: 30),
child: Row(
children: <Widget>[
const Icon(Icons.check_circle_outline,
color: RallyColors.buttonColor),
const SizedBox(width: 12),
Text(GalleryLocalizations.of(context)!.rallyLoginRememberMe),
const Expanded(child: SizedBox.shrink()),
_FilledButton(
text: GalleryLocalizations.of(context)!.rallyLoginButtonLogin,
onTap: onTap,
),
],
),
),
);
}
}
class _BorderButton extends StatelessWidget {
const _BorderButton({required this.text});
final String text;
@override
Widget build(BuildContext context) {
return OutlinedButton(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(color: RallyColors.buttonColor),
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 24),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
onPressed: () {
Navigator.of(context).restorablePushNamed(RallyApp.homeRoute);
},
child: Text(text),
);
}
}
class _FilledButton extends StatelessWidget {
const _FilledButton({required this.text, required this.onTap});
final String text;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.black,
backgroundColor: RallyColors.buttonColor,
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 24),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
onPressed: onTap,
child: Row(
children: <Widget>[
const Icon(Icons.lock),
const SizedBox(width: 6),
Text(text),
],
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/rally/login.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/login.dart",
"repo_id": "flutter",
"token_count": 5241
} | 539 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class Email {
Email({
required this.id,
required this.avatar,
this.sender = '',
this.time = '',
this.subject = '',
this.message = '',
this.recipients = '',
this.containsPictures = false,
});
final int id;
final String sender;
final String time;
final String subject;
final String message;
final String avatar;
final String recipients;
final bool containsPictures;
}
class InboxEmail extends Email {
InboxEmail({
required super.id,
required super.sender,
super.time,
super.subject,
super.message,
required super.avatar,
super.recipients,
super.containsPictures,
this.inboxType = InboxType.normal,
});
InboxType inboxType;
}
// The different mailbox pages that the Reply app contains.
enum MailboxPageType {
inbox,
starred,
sent,
trash,
spam,
drafts,
}
// Different types of mail that can be sent to the inbox.
enum InboxType {
normal,
spam,
}
| flutter/dev/integration_tests/new_gallery/lib/studies/reply/model/email_model.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/model/email_model.dart",
"repo_id": "flutter",
"token_count": 385
} | 540 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../layout/adaptive.dart';
class PageStatus extends InheritedWidget {
const PageStatus({
super.key,
required this.cartController,
required this.menuController,
required super.child,
});
final AnimationController cartController;
final AnimationController menuController;
static PageStatus? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<PageStatus>();
}
@override
bool updateShouldNotify(PageStatus oldWidget) =>
oldWidget.cartController != cartController ||
oldWidget.menuController != menuController;
}
bool productPageIsVisible(BuildContext context) {
return _cartControllerOf(context).isDismissed &&
(_menuControllerOf(context).isCompleted || isDisplayDesktop(context));
}
bool menuPageIsVisible(BuildContext context) {
return _cartControllerOf(context).isDismissed &&
(_menuControllerOf(context).isDismissed || isDisplayDesktop(context));
}
bool cartPageIsVisible(BuildContext context) {
return _cartControllerOf(context).isCompleted;
}
AnimationController _cartControllerOf(BuildContext context) {
return PageStatus.of(context)!.cartController;
}
AnimationController _menuControllerOf(BuildContext context) {
return PageStatus.of(context)!.menuController;
}
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/page_status.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/page_status.dart",
"repo_id": "flutter",
"token_count": 430
} | 541 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class GalleryThemeData {
static const Color _lightFillColor = Colors.black;
static const Color _darkFillColor = Colors.white;
static final Color _lightFocusColor = Colors.black.withOpacity(0.12);
static final Color _darkFocusColor = Colors.white.withOpacity(0.12);
static ThemeData lightThemeData =
themeData(lightColorScheme, _lightFocusColor);
static ThemeData darkThemeData = themeData(darkColorScheme, _darkFocusColor);
static ThemeData themeData(ColorScheme colorScheme, Color focusColor) {
return ThemeData(
colorScheme: colorScheme,
textTheme: _textTheme,
appBarTheme: AppBarTheme(
backgroundColor: colorScheme.background,
elevation: 0,
iconTheme: IconThemeData(color: colorScheme.primary),
),
iconTheme: IconThemeData(color: colorScheme.onPrimary),
canvasColor: colorScheme.background,
scaffoldBackgroundColor: colorScheme.background,
highlightColor: Colors.transparent,
focusColor: focusColor,
snackBarTheme: SnackBarThemeData(
behavior: SnackBarBehavior.floating,
backgroundColor: Color.alphaBlend(
_lightFillColor.withOpacity(0.80),
_darkFillColor,
),
contentTextStyle: _textTheme.titleMedium!.apply(color: _darkFillColor),
),
);
}
static const ColorScheme lightColorScheme = ColorScheme(
primary: Color(0xFFB93C5D),
primaryContainer: Color(0xFF117378),
secondary: Color(0xFFEFF3F3),
secondaryContainer: Color(0xFFFAFBFB),
background: Color(0xFFE6EBEB),
surface: Color(0xFFFAFBFB),
onBackground: Colors.white,
error: _lightFillColor,
onError: _lightFillColor,
onPrimary: _lightFillColor,
onSecondary: Color(0xFF322942),
onSurface: Color(0xFF241E30),
brightness: Brightness.light,
);
static const ColorScheme darkColorScheme = ColorScheme(
primary: Color(0xFFFF8383),
primaryContainer: Color(0xFF1CDEC9),
secondary: Color(0xFF4D1F7C),
secondaryContainer: Color(0xFF451B6F),
background: Color(0xFF241E30),
surface: Color(0xFF1F1929),
onBackground: Color(0x0DFFFFFF), // White with 0.05 opacity
error: _darkFillColor,
onError: _darkFillColor,
onPrimary: _darkFillColor,
onSecondary: _darkFillColor,
onSurface: _darkFillColor,
brightness: Brightness.dark,
);
static const FontWeight _regular = FontWeight.w400;
static const FontWeight _medium = FontWeight.w500;
static const FontWeight _semiBold = FontWeight.w600;
static const FontWeight _bold = FontWeight.w700;
static final TextTheme _textTheme = TextTheme(
headlineMedium: GoogleFonts.montserrat(fontWeight: _bold, fontSize: 20.0),
bodySmall: GoogleFonts.oswald(fontWeight: _semiBold, fontSize: 16.0),
headlineSmall: GoogleFonts.oswald(fontWeight: _medium, fontSize: 16.0),
titleMedium: GoogleFonts.montserrat(fontWeight: _medium, fontSize: 16.0),
labelSmall: GoogleFonts.montserrat(fontWeight: _medium, fontSize: 12.0),
bodyLarge: GoogleFonts.montserrat(fontWeight: _regular, fontSize: 14.0),
titleSmall: GoogleFonts.montserrat(fontWeight: _medium, fontSize: 14.0),
bodyMedium: GoogleFonts.montserrat(fontWeight: _regular, fontSize: 16.0),
titleLarge: GoogleFonts.montserrat(fontWeight: _bold, fontSize: 16.0),
labelLarge: GoogleFonts.montserrat(fontWeight: _semiBold, fontSize: 14.0),
);
}
| flutter/dev/integration_tests/new_gallery/lib/themes/gallery_theme_data.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/themes/gallery_theme_data.dart",
"repo_id": "flutter",
"token_count": 1334
} | 542 |
#include "Generated.xcconfig"
| flutter/dev/integration_tests/platform_interaction/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/integration_tests/platform_interaction/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 543 |
// Copyright 2014 The Flutter 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:async';
import 'package:flutter/material.dart';
enum TestStatus { ok, pending, failed, complete }
typedef TestStep = Future<TestStepResult> Function();
const String nothing = '-';
class TestStepResult {
const TestStepResult(this.name, this.description, this.status);
factory TestStepResult.fromSnapshot(AsyncSnapshot<TestStepResult> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return const TestStepResult('Not started', nothing, TestStatus.ok);
case ConnectionState.waiting:
return const TestStepResult('Executing', nothing, TestStatus.pending);
case ConnectionState.done:
if (snapshot.hasData) {
return snapshot.data!;
} else {
final Object? result = snapshot.error;
return result! as TestStepResult;
}
case ConnectionState.active:
throw 'Unsupported state ${snapshot.connectionState}';
}
}
final String name;
final String description;
final TestStatus status;
static const TextStyle normal = TextStyle(height: 1.0);
static const TextStyle bold = TextStyle(fontWeight: FontWeight.bold, height: 1.0);
static const TestStepResult complete = TestStepResult(
'Test complete',
nothing,
TestStatus.complete,
);
Widget asWidget(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Step: $name', style: bold),
Text(description, style: normal),
const Text(' ', style: normal),
Text(
status.toString().substring('TestStatus.'.length),
key: ValueKey<String>(
status == TestStatus.pending ? 'nostatus' : 'status'),
style: bold,
),
],
);
}
}
| flutter/dev/integration_tests/platform_interaction/lib/src/test_step.dart/0 | {
"file_path": "flutter/dev/integration_tests/platform_interaction/lib/src/test_step.dart",
"repo_id": "flutter",
"token_count": 705
} | 544 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:release_smoke_test/main.dart' as smoke;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Hello world smoke test', (WidgetTester tester) async {
smoke.main(); // builds the app and schedules a frame but doesn't trigger one
await tester.pump(); // triggers a frame
expect(find.text('Hello, world!'), findsOneWidget);
});
}
| flutter/dev/integration_tests/release_smoke_test/test_adapter/hello_world_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/release_smoke_test/test_adapter/hello_world_test.dart",
"repo_id": "flutter",
"token_count": 201
} | 545 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
key: Key('mainapp'),
title: 'Platform Test',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (defaultTargetPlatform == TargetPlatform.macOS)
const Text(
'I am running on MacOS',
key: Key('macOSKey'),
),
if (defaultTargetPlatform == TargetPlatform.iOS)
const Text(
'I am running on MacOS',
key: Key('iOSKey'),
),
if (defaultTargetPlatform == TargetPlatform.android)
const Text(
'I am running on Android',
key: Key('androidKey'),
),
],
),
),
);
}
}
| flutter/dev/integration_tests/web_e2e_tests/lib/target_platform_main.dart/0 | {
"file_path": "flutter/dev/integration_tests/web_e2e_tests/lib/target_platform_main.dart",
"repo_id": "flutter",
"token_count": 625
} | 546 |
// Copyright 2014 The Flutter 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:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter_driver/driver_extension.dart';
import 'windows.dart';
void drawHelloWorld(ui.FlutterView view) {
final ui.ParagraphStyle style = ui.ParagraphStyle();
final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(style)
..addText('Hello world');
final ui.Paragraph paragraph = paragraphBuilder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 100.0));
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawParagraph(paragraph, ui.Offset.zero);
final ui.Picture picture = recorder.endRecording();
final ui.SceneBuilder sceneBuilder = ui.SceneBuilder()
..addPicture(ui.Offset.zero, picture)
..pop();
view.render(sceneBuilder.build());
}
Future<void> _waitUntilWindowVisible() async {
while (!await isWindowVisible()) {
await Future<void>.delayed(const Duration(milliseconds: 100));
}
}
void _expectVisible(bool current, bool expect, Completer<String> completer, int frameCount) {
if (current != expect) {
try {
throw 'Window should be ${expect ? 'visible' : 'hidden'} on frame $frameCount';
} catch (e) {
if (!completer.isCompleted) {
completer.completeError(e);
}
rethrow;
}
}
}
void main() async {
// TODO(goderbauer): Create a window if embedder doesn't provide an implicit view to draw into.
assert(ui.PlatformDispatcher.instance.implicitView != null);
final ui.FlutterView view = ui.PlatformDispatcher.instance.implicitView!;
// Create a completer to send the window visibility result back to the
// integration test.
final Completer<String> visibilityCompleter = Completer<String>();
enableFlutterDriverExtension(handler: (String? message) async {
if (message == 'verifyWindowVisibility') {
return visibilityCompleter.future;
} else if (message == 'verifyTheme') {
final bool app = await isAppDarkModeEnabled();
final bool system = await isSystemDarkModeEnabled();
return (app == system)
? 'success'
: 'error: app dark mode ($app) does not match system dark mode ($system)';
} else if (message == 'verifyStringConversion') {
// Use a test string that contains code points that fit in both 8 and 16 bits.
// The code points are passed a list of integers through the method channel,
// which will use the UTF16 to UTF8 utility function to convert them to a
// std::string, which should equate to the original expected string.
const String expected = 'ABCℵ';
final Int32List codePoints = Int32List.fromList(expected.codeUnits);
final String converted = await testStringConversion(codePoints);
return (converted == expected)
? 'success'
: 'error: conversion of UTF16 string to UTF8 failed, expected "${expected.codeUnits}" but got "${converted.codeUnits}"';
}
throw 'Unrecognized message: $message';
});
try {
if (await isWindowVisible()) {
throw 'Window should be hidden at startup';
}
int frameCount = 0;
ui.PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
// Our goal is to verify that it's `drawHelloWorld` that makes the window
// appear, not anything else. This requires checking the visibility right
// before drawing, but since `isWindowVisible` has to be async, and
// `FlutterView.render` (in `drawHelloWorld`) forbids async before it,
// this can not be done during a single onBeginFrame. However, we can
// verify in separate frames to indirectly prove it, by ensuring that
// no other mechanism can affect isWindowVisible in the first frame at all.
frameCount += 1;
switch (frameCount) {
// The 1st frame: render nothing, just verify that the window is hidden.
case 1:
isWindowVisible().then((bool visible) {
_expectVisible(visible, false, visibilityCompleter, frameCount);
ui.PlatformDispatcher.instance.scheduleFrame();
});
// The 2nd frame: render, which makes the window appear.
case 2:
drawHelloWorld(view);
_waitUntilWindowVisible().then((_) {
if (!visibilityCompleter.isCompleted) {
visibilityCompleter.complete('success');
}
});
// Others, in case requested to render.
default:
drawHelloWorld(view);
}
};
} catch (e) {
visibilityCompleter.completeError(e);
rethrow;
}
ui.PlatformDispatcher.instance.scheduleFrame();
}
| flutter/dev/integration_tests/windows_startup_test/lib/main.dart/0 | {
"file_path": "flutter/dev/integration_tests/windows_startup_test/lib/main.dart",
"repo_id": "flutter",
"token_count": 1673
} | 547 |
// Copyright 2014 The Flutter 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';
class CardModel {
CardModel(this.value, this.height) :
textController = TextEditingController(text: 'Item $value');
int value;
double height;
int get color => ((value % 9) + 1) * 100;
final TextEditingController textController;
Key get key => ObjectKey(this);
}
class CardCollection extends StatefulWidget {
const CardCollection({super.key});
@override
CardCollectionState createState() => CardCollectionState();
}
class CardCollectionState extends State<CardCollection> {
static const TextStyle cardLabelStyle =
TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
// TODO(hansmuller): need a local image asset
static const String _sunshineURL = 'http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg';
static const double kCardMargins = 8.0;
static const double kFixedCardHeight = 100.0;
static const List<double> _cardHeights = <double>[
48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
];
MaterialColor _primaryColor = Colors.deepPurple;
List<CardModel> _cardModels = <CardModel>[];
DismissDirection _dismissDirection = DismissDirection.horizontal;
TextAlign _textAlign = TextAlign.center;
bool _editable = false;
bool _fixedSizeCards = false;
bool _sunshine = false;
bool _varyFontSizes = false;
void _updateCardSizes() {
if (_fixedSizeCards) {
return;
}
_cardModels = List<CardModel>.generate(
_cardModels.length,
(int i) {
_cardModels[i].height = _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i];
return _cardModels[i];
},
);
}
void _initVariableSizedCardModels() {
_cardModels = List<CardModel>.generate(
_cardHeights.length,
(int i) => CardModel(i, _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i]),
);
}
void _initFixedSizedCardModels() {
const int cardCount = 27;
_cardModels = List<CardModel>.generate(
cardCount,
(int i) => CardModel(i, kFixedCardHeight),
);
}
void _initCardModels() {
if (_fixedSizeCards) {
_initFixedSizedCardModels();
} else {
_initVariableSizedCardModels();
}
}
@override
void initState() {
super.initState();
_initCardModels();
}
void dismissCard(CardModel card) {
if (_cardModels.contains(card)) {
setState(() {
_cardModels.remove(card);
});
}
}
Widget _buildDrawer() {
return Drawer(
child: IconTheme(
data: const IconThemeData(color: Colors.black),
child: ListView(
children: <Widget>[
const DrawerHeader(child: Center(child: Text('Options'))),
buildDrawerCheckbox('Make card labels editable', _editable, _toggleEditable),
buildDrawerCheckbox('Fixed size cards', _fixedSizeCards, _toggleFixedSizeCards),
buildDrawerCheckbox('Let the sun shine', _sunshine, _toggleSunshine),
buildDrawerCheckbox('Vary font sizes', _varyFontSizes, _toggleVaryFontSizes, enabled: !_editable),
const Divider(),
buildDrawerColorRadioItem('Deep Purple', Colors.deepPurple, _primaryColor, _selectColor),
buildDrawerColorRadioItem('Green', Colors.green, _primaryColor, _selectColor),
buildDrawerColorRadioItem('Amber', Colors.amber, _primaryColor, _selectColor),
buildDrawerColorRadioItem('Teal', Colors.teal, _primaryColor, _selectColor),
const Divider(),
buildDrawerDirectionRadioItem('Dismiss horizontally', DismissDirection.horizontal, _dismissDirection, _changeDismissDirection, icon: Icons.code),
buildDrawerDirectionRadioItem('Dismiss left', DismissDirection.endToStart, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_back),
buildDrawerDirectionRadioItem('Dismiss right', DismissDirection.startToEnd, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_forward),
const Divider(),
buildFontRadioItem('Left-align text', TextAlign.left, _textAlign, _changeTextAlign, icon: Icons.format_align_left, enabled: !_editable),
buildFontRadioItem('Center-align text', TextAlign.center, _textAlign, _changeTextAlign, icon: Icons.format_align_center, enabled: !_editable),
buildFontRadioItem('Right-align text', TextAlign.right, _textAlign, _changeTextAlign, icon: Icons.format_align_right, enabled: !_editable),
const Divider(),
ListTile(
leading: const Icon(Icons.dvr),
onTap: () { debugDumpApp(); debugDumpRenderTree(); },
title: const Text('Dump App to Console'),
),
],
),
),
);
}
String _dismissDirectionText(DismissDirection direction) {
final String s = direction.toString();
return "dismiss ${s.substring(s.indexOf('.') + 1)}";
}
void _toggleEditable() {
setState(() {
_editable = !_editable;
_updateCardSizes();
});
}
void _toggleFixedSizeCards() {
setState(() {
_fixedSizeCards = !_fixedSizeCards;
_initCardModels();
});
}
void _toggleSunshine() {
setState(() {
_sunshine = !_sunshine;
});
}
void _toggleVaryFontSizes() {
setState(() {
_varyFontSizes = !_varyFontSizes;
});
}
void _selectColor(MaterialColor? selection) {
setState(() {
_primaryColor = selection!;
});
}
void _changeDismissDirection(DismissDirection? newDismissDirection) {
setState(() {
_dismissDirection = newDismissDirection!;
});
}
void _changeTextAlign(TextAlign? newTextAlign) {
setState(() {
_textAlign = newTextAlign!;
});
}
Widget buildDrawerCheckbox(String label, bool value, void Function() callback, { bool enabled = true }) {
return ListTile(
onTap: enabled ? callback : null,
title: Text(label),
trailing: Checkbox(
value: value,
onChanged: enabled ? (_) { callback(); } : null,
),
);
}
Widget buildDrawerColorRadioItem(String label, MaterialColor itemValue, MaterialColor currentValue, ValueChanged<MaterialColor?> onChanged, { IconData? icon, bool enabled = true }) {
return ListTile(
leading: Icon(icon),
title: Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
trailing: Radio<MaterialColor>(
value: itemValue,
groupValue: currentValue,
onChanged: enabled ? onChanged : null,
),
);
}
Widget buildDrawerDirectionRadioItem(String label, DismissDirection itemValue, DismissDirection currentValue, ValueChanged<DismissDirection?> onChanged, { IconData? icon, bool enabled = true }) {
return ListTile(
leading: Icon(icon),
title: Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
trailing: Radio<DismissDirection>(
value: itemValue,
groupValue: currentValue,
onChanged: enabled ? onChanged : null,
),
);
}
Widget buildFontRadioItem(String label, TextAlign itemValue, TextAlign currentValue, ValueChanged<TextAlign?> onChanged, { IconData? icon, bool enabled = true }) {
return ListTile(
leading: Icon(icon),
title: Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
trailing: Radio<TextAlign>(
value: itemValue,
groupValue: currentValue,
onChanged: enabled ? onChanged : null,
),
);
}
AppBar _buildAppBar(BuildContext context) {
return AppBar(
actions: <Widget>[
Text(_dismissDirectionText(_dismissDirection)),
],
flexibleSpace: Container(
padding: const EdgeInsets.only(left: 72.0),
height: 128.0,
alignment: const Alignment(-1.0, 0.5),
child: Text('Swipe Away: ${_cardModels.length}', style: Theme.of(context).primaryTextTheme.titleLarge),
),
);
}
Widget _buildCard(BuildContext context, int index) {
final CardModel cardModel = _cardModels[index];
final Widget card = Dismissible(
key: ObjectKey(cardModel),
direction: _dismissDirection,
onDismissed: (DismissDirection direction) { dismissCard(cardModel); },
child: Card(
color: _primaryColor[cardModel.color],
child: Container(
height: cardModel.height,
padding: const EdgeInsets.all(kCardMargins),
child: _editable ?
Center(
child: TextField(
key: GlobalObjectKey(cardModel),
controller: cardModel.textController,
),
)
: DefaultTextStyle.merge(
style: cardLabelStyle.copyWith(
fontSize: _varyFontSizes ? 5.0 + index : null
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(cardModel.textController.text, textAlign: _textAlign),
],
),
),
),
),
);
String backgroundMessage;
switch (_dismissDirection) {
case DismissDirection.horizontal:
backgroundMessage = 'Swipe in either direction';
case DismissDirection.endToStart:
backgroundMessage = 'Swipe left to dismiss';
case DismissDirection.startToEnd:
backgroundMessage = 'Swipe right to dismiss';
case DismissDirection.vertical:
case DismissDirection.up:
case DismissDirection.down:
case DismissDirection.none:
backgroundMessage = 'Unsupported dismissDirection';
}
// This icon is wrong in RTL.
Widget leftArrowIcon = const Icon(Icons.arrow_back, size: 36.0);
if (_dismissDirection == DismissDirection.startToEnd) {
leftArrowIcon = Opacity(opacity: 0.1, child: leftArrowIcon);
}
// This icon is wrong in RTL.
Widget rightArrowIcon = const Icon(Icons.arrow_forward, size: 36.0);
if (_dismissDirection == DismissDirection.endToStart) {
rightArrowIcon = Opacity(opacity: 0.1, child: rightArrowIcon);
}
final ThemeData theme = Theme.of(context);
final TextStyle? backgroundTextStyle = theme.primaryTextTheme.titleLarge;
// The background Widget appears behind the Dismissible card when the card
// moves to the left or right. The Positioned widget ensures that the
// size of the background,card Stack will be based only on the card. The
// Viewport ensures that when the card's resize animation occurs, the
// background (text and icons) will just be clipped, not resized.
final Widget background = Positioned.fill(
child: Container(
margin: const EdgeInsets.all(4.0),
child: SingleChildScrollView(
child: Container(
height: cardModel.height,
color: theme.primaryColor,
child: Row(
children: <Widget>[
leftArrowIcon,
Expanded(
child: Text(backgroundMessage,
style: backgroundTextStyle,
textAlign: TextAlign.center,
),
),
rightArrowIcon,
],
),
),
),
),
);
return IconTheme(
key: cardModel.key,
data: const IconThemeData(color: Colors.white),
child: Stack(children: <Widget>[background, card]),
);
}
Shader _createShader(Rect bounds) {
return const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[Color(0x00FFFFFF), Color(0xFFFFFFFF)],
stops: <double>[0.1, 0.35],
)
.createShader(bounds);
}
@override
Widget build(BuildContext context) {
Widget cardCollection = ListView.builder(
itemExtent: _fixedSizeCards ? kFixedCardHeight : null,
itemCount: _cardModels.length,
itemBuilder: _buildCard,
);
if (_sunshine) {
cardCollection = Stack(
children: <Widget>[
Column(children: <Widget>[Image.network(_sunshineURL)]),
ShaderMask(shaderCallback: _createShader, child: cardCollection),
],
);
}
final Widget body = Container(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
color: _primaryColor.shade50,
child: cardCollection,
);
return Theme(
data: ThemeData(
primarySwatch: _primaryColor,
),
child: Scaffold(
appBar: _buildAppBar(context),
drawer: _buildDrawer(),
body: body,
),
);
}
}
void main() {
runApp(const MaterialApp(
title: 'Cards',
home: CardCollection(),
));
}
| flutter/dev/manual_tests/lib/card_collection.dart/0 | {
"file_path": "flutter/dev/manual_tests/lib/card_collection.dart",
"repo_id": "flutter",
"token_count": 5400
} | 548 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:manual_tests/color_testing_demo.dart' as color_testing_demo;
import 'mock_image_http.dart';
void main() {
testWidgets('Color testing demo smoke test', (WidgetTester tester) async {
HttpOverrides.runZoned<Future<void>>(() async {
color_testing_demo.main(); // builds the app and schedules a frame but doesn't trigger one
await tester.pump(); // see https://github.com/flutter/flutter/issues/1865
await tester.pump(); // triggers a frame
await tester.dragFrom(const Offset(0.0, 500.0), Offset.zero); // scrolls down
await tester.pump();
await tester.dragFrom(const Offset(0.0, 500.0), Offset.zero); // scrolls down
await tester.pump();
}, createHttpClient: createMockImageHttpClient);
});
}
| flutter/dev/manual_tests/test/color_testing_demo_test.dart/0 | {
"file_path": "flutter/dev/manual_tests/test/color_testing_demo_test.dart",
"repo_id": "flutter",
"token_count": 352
} | 549 |
{@inject-html}
<a name="{{id}}"></a>
<div class="snippet snippet-container anchor-container" id="longSnippet{{serial}}">
{{description}}
<a class="anchor-button-overlay anchor-button" title="Copy link to clipboard"
onmouseenter="fixHref(this, '{{id}}');" onclick="fixHref(this, '{{id}}'); copyStringToClipboard(this.href);"
href="#">
<i class="material-icons anchor-image">link</i>
</a>
<div class="snippet-description">
<p>To create a local project with this code sample, run:<br />
<span class="snippet-create-command">flutter create --sample={{id}} mysample</span>
</p>
</div>
<iframe class="snippet-dartpad"
src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id={{id}}&channel={{channel}}">
</iframe>
</div>
{@end-inject-html} | flutter/dev/snippets/config/skeletons/dartpad-sample.html/0 | {
"file_path": "flutter/dev/snippets/config/skeletons/dartpad-sample.html",
"repo_id": "flutter",
"token_count": 353
} | 550 |
{
"version": "v0_206",
"md.comp.elevated-button.container.color": "surfaceContainerLow",
"md.comp.elevated-button.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-button.container.height": 40.0,
"md.comp.elevated-button.container.shadow-color": "shadow",
"md.comp.elevated-button.container.shape": "md.sys.shape.corner.full",
"md.comp.elevated-button.disabled.container.color": "onSurface",
"md.comp.elevated-button.disabled.container.elevation": "md.sys.elevation.level0",
"md.comp.elevated-button.disabled.container.opacity": 0.12,
"md.comp.elevated-button.disabled.label-text.color": "onSurface",
"md.comp.elevated-button.disabled.label-text.opacity": 0.38,
"md.comp.elevated-button.focus.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-button.focus.indicator.color": "secondary",
"md.comp.elevated-button.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.elevated-button.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.elevated-button.focus.label-text.color": "primary",
"md.comp.elevated-button.focus.state-layer.color": "primary",
"md.comp.elevated-button.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.elevated-button.hover.container.elevation": "md.sys.elevation.level2",
"md.comp.elevated-button.hover.label-text.color": "primary",
"md.comp.elevated-button.hover.state-layer.color": "primary",
"md.comp.elevated-button.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.elevated-button.label-text.color": "primary",
"md.comp.elevated-button.label-text.text-style": "labelLarge",
"md.comp.elevated-button.pressed.container.elevation": "md.sys.elevation.level1",
"md.comp.elevated-button.pressed.label-text.color": "primary",
"md.comp.elevated-button.pressed.state-layer.color": "primary",
"md.comp.elevated-button.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.elevated-button.with-icon.disabled.icon.color": "onSurface",
"md.comp.elevated-button.with-icon.disabled.icon.opacity": 0.38,
"md.comp.elevated-button.with-icon.focus.icon.color": "primary",
"md.comp.elevated-button.with-icon.hover.icon.color": "primary",
"md.comp.elevated-button.with-icon.icon.color": "primary",
"md.comp.elevated-button.with-icon.icon.size": 18.0,
"md.comp.elevated-button.with-icon.pressed.icon.color": "primary"
}
| flutter/dev/tools/gen_defaults/data/button_elevated.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/button_elevated.json",
"repo_id": "flutter",
"token_count": 960
} | 551 |
{
"version": "v0_206",
"md.comp.date-picker.docked.container.color": "surfaceContainerHigh",
"md.comp.date-picker.docked.container.elevation": "md.sys.elevation.level3",
"md.comp.date-picker.docked.container.height": 456.0,
"md.comp.date-picker.docked.container.shape": "md.sys.shape.corner.large",
"md.comp.date-picker.docked.container.width": 360.0,
"md.comp.date-picker.docked.date.container.height": 48.0,
"md.comp.date-picker.docked.date.container.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.docked.date.container.width": 48.0,
"md.comp.date-picker.docked.date.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.date-picker.docked.date.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.date-picker.docked.date.label-text.text-style": "bodyLarge",
"md.comp.date-picker.docked.date.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.date-picker.docked.date.selected.container.color": "primary",
"md.comp.date-picker.docked.date.selected.focus.state-layer.color": "onPrimary",
"md.comp.date-picker.docked.date.selected.hover.state-layer.color": "onPrimary",
"md.comp.date-picker.docked.date.selected.label-text.color": "onPrimary",
"md.comp.date-picker.docked.date.selected.pressed.state-layer.color": "onPrimary",
"md.comp.date-picker.docked.date.state-layer.height": 40.0,
"md.comp.date-picker.docked.date.state-layer.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.docked.date.state-layer.width": 40.0,
"md.comp.date-picker.docked.date.today.container.outline.color": "primary",
"md.comp.date-picker.docked.date.today.container.outline.width": 1.0,
"md.comp.date-picker.docked.date.today.focus.state-layer.color": "primary",
"md.comp.date-picker.docked.date.today.hover.state-layer.color": "primary",
"md.comp.date-picker.docked.date.today.label-text.color": "primary",
"md.comp.date-picker.docked.date.today.pressed.state-layer.color": "primary",
"md.comp.date-picker.docked.date.unselected.focus.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.docked.date.unselected.hover.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.docked.date.unselected.label-text.color": "onSurface",
"md.comp.date-picker.docked.date.unselected.outside-month.label-text.color": "onSurfaceVariant",
"md.comp.date-picker.docked.date.unselected.pressed.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.docked.header.height": 64.0,
"md.comp.date-picker.docked.menu-button.container.height": 40.0,
"md.comp.date-picker.docked.menu-button.container.shape": "md.sys.shape.corner.full",
"md.comp.date-picker.docked.menu-button.disabled.icon.color": "onSurface",
"md.comp.date-picker.docked.menu-button.disabled.icon.opacity": 0.38,
"md.comp.date-picker.docked.menu-button.disabled.label-text.color": "onSurface",
"md.comp.date-picker.docked.menu-button.disabled.label-text.opacity": 0.38,
"md.comp.date-picker.docked.menu-button.focus.icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.focus.label-text.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.focus.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.date-picker.docked.menu-button.hover.icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.hover.label-text.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.hover.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.date-picker.docked.menu-button.icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.icon.size": 18.0,
"md.comp.date-picker.docked.menu-button.label-text.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.label-text.text-style": "labelLarge",
"md.comp.date-picker.docked.menu-button.pressed.icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.pressed.label-text.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.pressed.state-layer.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu-button.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.date-picker.docked.menu.list-item.container.height": 48.0,
"md.comp.date-picker.docked.menu.list-item.focus.label-text.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.focus.state-layer.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.date-picker.docked.menu.list-item.hover.label-text.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.hover.state-layer.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.date-picker.docked.menu.list-item.label-text.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.label-text.text-style": "bodyLarge",
"md.comp.date-picker.docked.menu.list-item.pressed.label-text.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.pressed.state-layer.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.date-picker.docked.menu.list-item.selected.container.color": "surfaceVariant",
"md.comp.date-picker.docked.menu.list-item.selected.focus.leading-icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu.list-item.selected.hover.leading-icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.menu.list-item.selected.leading-icon.color": "onSurface",
"md.comp.date-picker.docked.menu.list-item.selected.leading-icon.size": 24.0,
"md.comp.date-picker.docked.menu.list-item.selected.pressed.leading-icon.color": "onSurfaceVariant",
"md.comp.date-picker.docked.weekdays.label-text.color": "onSurface",
"md.comp.date-picker.docked.weekdays.label-text.text-style": "bodyLarge"
}
| flutter/dev/tools/gen_defaults/data/date_picker_docked.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/date_picker_docked.json",
"repo_id": "flutter",
"token_count": 2444
} | 552 |
{
"version": "v0_206",
"md.comp.menu.container.color": "surfaceContainer",
"md.comp.menu.container.elevation": "md.sys.elevation.level2",
"md.comp.menu.container.shadow-color": "shadow",
"md.comp.menu.container.shape": "md.sys.shape.corner.extra-small",
"md.comp.menu.focus.indicator.color": "secondary",
"md.comp.menu.focus.indicator.outline.offset": "md.sys.state.focus-indicator.inner-offset",
"md.comp.menu.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.menu.list-item.selected.container.color": "secondaryContainer",
"md.comp.menu.list-item.selected.label-text.color": "onSecondaryContainer",
"md.comp.menu.list-item.selected.with-leading-icon.trailing-icon.color": "onSecondaryContainer",
"md.comp.menu.menu-list-item-with-leading-icon-icon-color": "onSecondaryContainer"
}
| flutter/dev/tools/gen_defaults/data/menu.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/menu.json",
"repo_id": "flutter",
"token_count": 307
} | 553 |
{
"version": "v0_206",
"md.comp.slider.active.track.color": "primary",
"md.comp.slider.active.track.height": 4.0,
"md.comp.slider.active.track.shape": "md.sys.shape.corner.full",
"md.comp.slider.disabled.active.track.color": "onSurface",
"md.comp.slider.disabled.active.track.opacity": 0.38,
"md.comp.slider.disabled.handle.color": "onSurface",
"md.comp.slider.disabled.handle.elevation": "md.sys.elevation.level0",
"md.comp.slider.disabled.handle.opacity": 0.38,
"md.comp.slider.disabled.inactive.track.color": "onSurface",
"md.comp.slider.disabled.inactive.track.opacity": 0.12,
"md.comp.slider.focus.handle.color": "primary",
"md.comp.slider.focus.state-layer.color": "primary",
"md.comp.slider.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.slider.handle.color": "primary",
"md.comp.slider.handle.elevation": "md.sys.elevation.level1",
"md.comp.slider.handle.height": 20.0,
"md.comp.slider.handle.shadow-color": "shadow",
"md.comp.slider.handle.shape": "md.sys.shape.corner.full",
"md.comp.slider.handle.width": 20.0,
"md.comp.slider.hover.handle.color": "primary",
"md.comp.slider.hover.state-layer.color": "primary",
"md.comp.slider.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.slider.inactive.track.color": "surfaceContainerHighest",
"md.comp.slider.inactive.track.height": 4.0,
"md.comp.slider.inactive.track.shape": "md.sys.shape.corner.full",
"md.comp.slider.label.container.color": "primary",
"md.comp.slider.label.container.elevation": "md.sys.elevation.level0",
"md.comp.slider.label.container.height": 28.0,
"md.comp.slider.label.label-text.color": "onPrimary",
"md.comp.slider.label.label-text.text-style": "labelMedium",
"md.comp.slider.pressed.handle.color": "primary",
"md.comp.slider.pressed.state-layer.color": "primary",
"md.comp.slider.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.slider.state-layer.size": 40.0,
"md.comp.slider.track.elevation": "md.sys.elevation.level0",
"md.comp.slider.with-overlap.handle.outline.color": "onPrimary",
"md.comp.slider.with-overlap.handle.outline.width": 1.0,
"md.comp.slider.with-tick-marks.active.container.color": "onPrimary",
"md.comp.slider.with-tick-marks.active.container.opacity": 0.38,
"md.comp.slider.with-tick-marks.container.shape": "md.sys.shape.corner.full",
"md.comp.slider.with-tick-marks.container.size": 2.0,
"md.comp.slider.with-tick-marks.disabled.container.color": "onSurface",
"md.comp.slider.with-tick-marks.disabled.container.opacity": 0.38,
"md.comp.slider.with-tick-marks.inactive.container.color": "onSurfaceVariant",
"md.comp.slider.with-tick-marks.inactive.container.opacity": 0.38
}
| flutter/dev/tools/gen_defaults/data/slider.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/slider.json",
"repo_id": "flutter",
"token_count": 1107
} | 554 |
// Copyright 2014 The Flutter 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 'template.dart';
class BannerTemplate extends TokenTemplate {
const BannerTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
super.textThemePrefix = '_textTheme.'
});
@override
String generate() => '''
class _${blockName}DefaultsM3 extends MaterialBannerThemeData {
_${blockName}DefaultsM3(this.context)
: super(elevation: ${elevation("md.comp.banner.container")});
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
@override
Color? get backgroundColor => ${componentColor("md.comp.banner.container")};
@override
Color? get surfaceTintColor => ${colorOrTransparent("md.comp.banner.container.surface-tint-layer.color")};
@override
Color? get dividerColor => ${color("md.comp.divider.color")};
@override
TextStyle? get contentTextStyle => ${textStyle("md.comp.banner.supporting-text")};
}
''';
}
| flutter/dev/tools/gen_defaults/lib/banner_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/banner_template.dart",
"repo_id": "flutter",
"token_count": 372
} | 555 |
// Copyright 2014 The Flutter 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 'template.dart';
class SurfaceTintTemplate extends TokenTemplate {
const SurfaceTintTemplate(super.blockName, super.fileName, super.tokens);
@override
String generate() => '''
// Surface tint opacities based on elevations according to the
// Material Design 3 specification:
// https://m3.material.io/styles/color/the-color-system/color-roles
// Ordered by increasing elevation.
const List<_ElevationOpacity> _surfaceTintElevationOpacities = <_ElevationOpacity>[
_ElevationOpacity(${getToken('md.sys.elevation.level0')}, 0.0), // Elevation level 0
_ElevationOpacity(${getToken('md.sys.elevation.level1')}, 0.05), // Elevation level 1
_ElevationOpacity(${getToken('md.sys.elevation.level2')}, 0.08), // Elevation level 2
_ElevationOpacity(${getToken('md.sys.elevation.level3')}, 0.11), // Elevation level 3
_ElevationOpacity(${getToken('md.sys.elevation.level4')}, 0.12), // Elevation level 4
_ElevationOpacity(${getToken('md.sys.elevation.level5')}, 0.14), // Elevation level 5
];
''';
}
| flutter/dev/tools/gen_defaults/lib/surface_tint.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/surface_tint.dart",
"repo_id": "flutter",
"token_count": 401
} | 556 |
package io.flutter.embedding.android;
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by flutter/flutter@dev/tools/gen_keycodes/bin/gen_keycodes.dart and
// should not be edited directly.
//
// Edit the template dev/tools/gen_keycodes/data/android_keyboard_map_java.tmpl instead.
// See dev/tools/gen_keycodes/README.md for more information.
import android.view.KeyEvent;
import java.util.HashMap;
/** Static information used by {@link KeyEmbedderResponder}. */
public class KeyboardMap {
/** A physicalKey-logicalKey pair used to define mappings. */
public static class KeyPair {
public KeyPair(long physicalKey, long logicalKey) {
this.physicalKey = physicalKey;
this.logicalKey = logicalKey;
}
public long physicalKey;
public long logicalKey;
}
/**
* An immutable configuration item that defines how to synchronize pressing modifiers (such as
* Shift or Ctrl), so that the {@link KeyEmbedderResponder} must synthesize events until the
* combined pressing state of {@link keys} matches the true meta state masked by {@link mask}.
*/
public static class PressingGoal {
public PressingGoal(int mask, KeyPair[] keys) {
this.mask = mask;
this.keys = keys;
}
public final int mask;
public final KeyPair[] keys;
}
/**
* A configuration item that defines how to synchronize toggling modifiers (such as CapsLock), so
* that the {@link KeyEmbedderResponder} must synthesize events until the enabling state of the
* key matches the true meta state masked by {@link #mask}.
*
* <p>The objects of this class are mutable. The {@link #enabled} field will be used to store the
* current enabling state.
*/
public static class TogglingGoal {
public TogglingGoal(int mask, long physicalKey, long logicalKey) {
this.mask = mask;
this.physicalKey = physicalKey;
this.logicalKey = logicalKey;
}
public final int mask;
public final long physicalKey;
public final long logicalKey;
/**
* Used by {@link KeyEmbedderResponder} to store the current enabling state of this modifier.
*
* <p>Initialized as false.
*/
public boolean enabled = false;
}
/** Maps from Android scan codes {@link KeyEvent#getScanCode()} to Flutter physical keys. */
public static final HashMap<Long, Long> scanCodeToPhysical =
new HashMap<Long, Long>() {
private static final long serialVersionUID = 1L;
{
@@@ANDROID_SCAN_CODE_MAP@@@
}
};
/** Maps from Android key codes {@link KeyEvent#getKeyCode()} to Flutter logical keys. */
public static final HashMap<Long, Long> keyCodeToLogical =
new HashMap<Long, Long>() {
private static final long serialVersionUID = 1L;
{
@@@ANDROID_KEY_CODE_MAP@@@
}
};
public static final PressingGoal[] pressingGoals =
new PressingGoal[] {
@@@PRESSING_GOALS@@@
};
/**
* A list of toggling modifiers that must be synchronized on each key event.
*
* <p>The list is not a static variable but constructed by a function, because {@link
* TogglingGoal} is mutable.
*/
public static TogglingGoal[] getTogglingGoals() {
return new TogglingGoal[] {
@@@TOGGLING_GOALS@@@
};
}
@@@MASK_CONSTANTS@@@
}
| flutter/dev/tools/gen_keycodes/data/android_keyboard_map_java.tmpl/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/android_keyboard_map_java.tmpl",
"repo_id": "flutter",
"token_count": 1168
} | 557 |
{
"Backquote": false,
"Backslash": false,
"BracketLeft": false,
"BracketRight": false,
"Comma": false,
"Digit0": true,
"Digit1": true,
"Digit2": true,
"Digit3": true,
"Digit4": true,
"Digit5": true,
"Digit6": true,
"Digit7": true,
"Digit8": true,
"Digit9": true,
"Equal": false,
"IntlBackslash": false,
"KeyA": true,
"KeyB": true,
"KeyC": true,
"KeyD": true,
"KeyE": true,
"KeyF": true,
"KeyG": true,
"KeyH": true,
"KeyI": true,
"KeyJ": true,
"KeyK": true,
"KeyL": true,
"KeyM": true,
"KeyN": true,
"KeyO": true,
"KeyP": true,
"KeyQ": true,
"KeyR": true,
"KeyS": true,
"KeyT": true,
"KeyU": true,
"KeyV": true,
"KeyW": true,
"KeyX": true,
"KeyY": true,
"KeyZ": true,
"Minus": false,
"Period": false,
"Quote": false,
"Semicolon": false,
"Slash": false,
"Space": false
}
| flutter/dev/tools/gen_keycodes/data/layout_goals.json/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/layout_goals.json",
"repo_id": "flutter",
"token_count": 508
} | 558 |
// Copyright 2014 The Flutter 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 'utils.dart';
class MaskConstant {
const MaskConstant({required this.name, required this.value, required this.description});
const MaskConstant.platform({required String platform, required int value})
: this(
name: '$platform Plane',
value: value,
description: 'The plane value for the private keys defined by the $platform embedding.'
);
final String name;
final int value;
final String description;
String get upperCamelName {
return name
.split(' ')
.map<String>((String word) => lowerCamelToUpperCamel(word.toLowerCase()))
.join();
}
String get lowerCamelName {
final String upperCamel = upperCamelName;
return upperCamel.substring(0, 1).toLowerCase() + upperCamel.substring(1);
}
}
const MaskConstant kValueMask = MaskConstant(
name: 'Value Mask',
value: 0x00FFFFFFFF,
description: 'Mask for the 32-bit value portion of the key code.',
);
const MaskConstant kPlaneMask = MaskConstant(
name: 'Plane Mask',
value: 0xFF00000000,
description: 'Mask for the plane prefix portion of the key code.',
);
const MaskConstant kUnicodePlane = MaskConstant(
name: 'Unicode Plane',
value: 0x0000000000,
description: 'The plane value for keys which have a Unicode representation.',
);
const MaskConstant kUnprintablePlane = MaskConstant(
name: 'Unprintable Plane',
value: 0x0100000000,
description: 'The plane value for keys defined by Chromium and does not have a Unicode representation.',
);
const MaskConstant kFlutterPlane = MaskConstant(
name: 'Flutter Plane',
value: 0x0200000000,
description: 'The plane value for keys defined by Flutter.',
);
const MaskConstant kStartOfPlatformPlanes = MaskConstant(
name: 'Start Of Platform Planes',
value: 0x1100000000,
description: 'The platform plane with the lowest mask value, beyond which the keys are considered autogenerated.',
);
const MaskConstant kAndroidPlane = MaskConstant.platform(
platform: 'Android',
value: 0x1100000000,
);
const MaskConstant kFuchsiaPlane = MaskConstant.platform(
platform: 'Fuchsia',
value: 0x1200000000,
);
const MaskConstant kIosPlane = MaskConstant.platform(
platform: 'iOS',
value: 0x1300000000,
);
const MaskConstant kMacosPlane = MaskConstant.platform(
platform: 'macOS',
value: 0x1400000000,
);
const MaskConstant kGtkPlane = MaskConstant.platform(
platform: 'Gtk',
value: 0x1500000000,
);
const MaskConstant kWindowsPlane = MaskConstant.platform(
platform: 'Windows',
value: 0x1600000000,
);
const MaskConstant kWebPlane = MaskConstant.platform(
platform: 'Web',
value: 0x1700000000,
);
const MaskConstant kGlfwPlane = MaskConstant.platform(
platform: 'GLFW',
value: 0x1800000000,
);
| flutter/dev/tools/gen_keycodes/lib/constants.dart/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/lib/constants.dart",
"repo_id": "flutter",
"token_count": 939
} | 559 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// The utility function `encodeKnArbFiles` replaces the material_kn.arb
// and cupertino_kn.arb files in flutter_localizations/packages/lib/src/l10n
// with versions where the contents of the localized strings have been
// replaced by JSON escapes. This is done because some of those strings
// contain characters that can crash Emacs on Linux. There is more information
// here: https://github.com/flutter/flutter/issues/36704 and in the README
// in flutter_localizations/packages/lib/src/l10n.
//
// This utility is run by `gen_localizations.dart` if --overwrite is passed
// in as an option.
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import '../localizations_utils.dart';
Map<String, dynamic> _loadBundle(File file) {
if (!FileSystemEntity.isFileSync(file.path)) {
exitWithError('Unable to find input file: ${file.path}');
}
return json.decode(file.readAsStringSync()) as Map<String, dynamic>;
}
void _encodeBundleTranslations(Map<String, dynamic> bundle) {
for (final String key in bundle.keys) {
// The ARB file resource "attributes" for foo are called @foo. Don't need
// to encode them.
if (key.startsWith('@')) {
continue;
}
final String translation = bundle[key] as String;
// Rewrite the string as a series of unicode characters in JSON format.
// Like "\u0012\u0123\u1234".
bundle[key] = translation.runes.map((int code) {
final String codeString = '00${code.toRadixString(16)}';
return '\\u${codeString.substring(codeString.length - 4)}';
}).join();
}
}
void _checkEncodedTranslations(Map<String, dynamic> encodedBundle, Map<String, dynamic> bundle) {
bool errorFound = false;
const JsonDecoder decoder = JsonDecoder();
for (final String key in bundle.keys) {
if (decoder.convert('"${encodedBundle[key]}"') != bundle[key]) {
stderr.writeln(' encodedTranslation for $key does not match original value "${bundle[key]}"');
errorFound = true;
}
}
if (errorFound) {
exitWithError('JSON unicode translation encoding failed');
}
}
void _rewriteBundle(File file, Map<String, dynamic> bundle) {
final StringBuffer contents = StringBuffer();
contents.writeln('{');
for (final String key in bundle.keys) {
contents.writeln(' "$key": "${bundle[key]}"${key == bundle.keys.last ? '' : ','}');
}
contents.writeln('}');
file.writeAsStringSync(contents.toString());
}
void encodeKnArbFiles(Directory directory) {
final File widgetsArbFile = File(path.join(directory.path, 'widgets_kn.arb'));
final File materialArbFile = File(path.join(directory.path, 'material_kn.arb'));
final File cupertinoArbFile = File(path.join(directory.path, 'cupertino_kn.arb'));
final Map<String, dynamic> widgetsBundle = _loadBundle(widgetsArbFile);
final Map<String, dynamic> materialBundle = _loadBundle(materialArbFile);
final Map<String, dynamic> cupertinoBundle = _loadBundle(cupertinoArbFile);
_encodeBundleTranslations(widgetsBundle);
_encodeBundleTranslations(materialBundle);
_encodeBundleTranslations(cupertinoBundle);
_checkEncodedTranslations(widgetsBundle, _loadBundle(widgetsArbFile));
_checkEncodedTranslations(materialBundle, _loadBundle(materialArbFile));
_checkEncodedTranslations(cupertinoBundle, _loadBundle(cupertinoArbFile));
_rewriteBundle(widgetsArbFile, widgetsBundle);
_rewriteBundle(materialArbFile, materialBundle);
_rewriteBundle(cupertinoArbFile, cupertinoBundle);
}
| flutter/dev/tools/localization/bin/encode_kn_arb_files.dart/0 | {
"file_path": "flutter/dev/tools/localization/bin/encode_kn_arb_files.dart",
"repo_id": "flutter",
"token_count": 1211
} | 560 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Regenerates a Dart file with a class containing IconData constants.
// See https://github.com/flutter/flutter/wiki/Updating-Material-Design-Fonts-&-Icons
// Should be idempotent with:
// dart dev/tools/update_icons.dart --new-codepoints bin/cache/artifacts/material_fonts/codepoints
import 'dart:collection';
import 'dart:convert' show LineSplitter;
import 'dart:io';
import 'package:args/args.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
const String _iconsPathOption = 'icons';
const String _iconsTemplatePathOption = 'icons-template';
const String _newCodepointsPathOption = 'new-codepoints';
const String _oldCodepointsPathOption = 'old-codepoints';
const String _fontFamilyOption = 'font-family';
const String _possibleStyleSuffixesOption = 'style-suffixes';
const String _classNameOption = 'class-name';
const String _enforceSafetyChecks = 'enforce-safety-checks';
const String _dryRunOption = 'dry-run';
const String _defaultIconsPath = 'packages/flutter/lib/src/material/icons.dart';
const String _defaultNewCodepointsPath = 'codepoints';
const String _defaultOldCodepointsPath = 'bin/cache/artifacts/material_fonts/codepoints';
const String _defaultFontFamily = 'MaterialIcons';
const List<String> _defaultPossibleStyleSuffixes = <String>[
'_outlined',
'_rounded',
'_sharp',
];
const String _defaultClassName = 'Icons';
const String _defaultDemoFilePath = '/tmp/new_icons_demo.dart';
const String _beginGeneratedMark = '// BEGIN GENERATED ICONS';
const String _endGeneratedMark = '// END GENERATED ICONS';
const String _beginPlatformAdaptiveGeneratedMark = '// BEGIN GENERATED PLATFORM ADAPTIVE ICONS';
const String _endPlatformAdaptiveGeneratedMark = '// END GENERATED PLATFORM ADAPTIVE ICONS';
const Map<String, List<String>> _platformAdaptiveIdentifiers = <String, List<String>>{
// Mapping of Flutter IDs to an Android/agnostic ID and an iOS ID.
// Flutter IDs can be anything, but should be chosen to be agnostic.
'arrow_back': <String>['arrow_back', 'arrow_back_ios'],
'arrow_forward': <String>['arrow_forward', 'arrow_forward_ios'],
'flip_camera': <String>['flip_camera_android', 'flip_camera_ios'],
'more': <String>['more_vert', 'more_horiz'],
'share': <String>['share', 'ios_share'],
};
// Rewrite certain Flutter IDs (numbers) using prefix matching.
const Map<String, String> _identifierPrefixRewrites = <String, String>{
'1': 'one_',
'2': 'two_',
'3': 'three_',
'4': 'four_',
'5': 'five_',
'6': 'six_',
'7': 'seven_',
'8': 'eight_',
'9': 'nine_',
'10': 'ten_',
'11': 'eleven_',
'12': 'twelve_',
'13': 'thirteen_',
'14': 'fourteen_',
'15': 'fifteen_',
'16': 'sixteen_',
'17': 'seventeen_',
'18': 'eighteen_',
'19': 'nineteen_',
'20': 'twenty_',
'21': 'twenty_one_',
'22': 'twenty_two_',
'23': 'twenty_three_',
'24': 'twenty_four_',
'30': 'thirty_',
'60': 'sixty_',
'123': 'onetwothree',
'360': 'threesixty',
'2d': 'twod',
'3d': 'threed',
'3d_rotation': 'threed_rotation',
};
// Rewrite certain Flutter IDs (reserved keywords) using exact matching.
const Map<String, String> _identifierExactRewrites = <String, String>{
'class': 'class_',
'new': 'new_',
'switch': 'switch_',
'try': 'try_sms_star',
'door_back': 'door_back_door',
'door_front': 'door_front_door',
};
const Set<String> _iconsMirroredWhenRTL = <String>{
// This list is obtained from:
// https://developers.google.com/fonts/docs/material_icons#which_icons_should_be_mirrored_for_rtl
'arrow_back',
'arrow_back_ios',
'arrow_forward',
'arrow_forward_ios',
'arrow_left',
'arrow_right',
'assignment',
'assignment_return',
'backspace',
'battery_unknown',
'call_made',
'call_merge',
'call_missed',
'call_missed_outgoing',
'call_received',
'call_split',
'chevron_left',
'chevron_right',
'chrome_reader_mode',
'device_unknown',
'dvr',
'event_note',
'featured_play_list',
'featured_video',
'first_page',
'flight_land',
'flight_takeoff',
'format_indent_decrease',
'format_indent_increase',
'format_list_bulleted',
'forward',
'functions',
'help',
'help_outline',
'input',
'keyboard_backspace',
'keyboard_tab',
'label',
'label_important',
'label_outline',
'last_page',
'launch',
'list',
'live_help',
'mobile_screen_share',
'multiline_chart',
'navigate_before',
'navigate_next',
'next_week',
'note',
'open_in',
'playlist_add',
'queue_music',
'redo',
'reply',
'reply_all',
'screen_share',
'send',
'short_text',
'show_chart',
'sort',
'star_half',
'subject',
'trending_flat',
'toc',
'trending_down',
'trending_up',
'undo',
'view_list',
'view_quilt',
'wrap_text',
};
void main(List<String> args) {
// If we're run from the `tools` dir, set the cwd to the repo root.
if (path.basename(Directory.current.path) == 'tools') {
Directory.current = Directory.current.parent.parent;
}
final ArgResults argResults = _handleArguments(args);
final File iconsFile = File(path.normalize(path.absolute(argResults[_iconsPathOption] as String)));
if (!iconsFile.existsSync()) {
stderr.writeln('Error: Icons file not found: ${iconsFile.path}');
exit(1);
}
final File iconsTemplateFile = File(path.normalize(path.absolute(argResults[_iconsTemplatePathOption] as String)));
if (!iconsTemplateFile.existsSync()) {
stderr.writeln('Error: Icons template file not found: ${iconsTemplateFile.path}');
exit(1);
}
final File newCodepointsFile = File(argResults[_newCodepointsPathOption] as String);
if (!newCodepointsFile.existsSync()) {
stderr.writeln('Error: New codepoints file not found: ${newCodepointsFile.path}');
exit(1);
}
final File oldCodepointsFile = File(argResults[_oldCodepointsPathOption] as String);
if (!oldCodepointsFile.existsSync()) {
stderr.writeln('Error: Old codepoints file not found: ${oldCodepointsFile.path}');
exit(1);
}
final String newCodepointsString = newCodepointsFile.readAsStringSync();
final Map<String, String> newTokenPairMap = stringToTokenPairMap(newCodepointsString);
final String oldCodepointsString = oldCodepointsFile.readAsStringSync();
final Map<String, String> oldTokenPairMap = stringToTokenPairMap(oldCodepointsString);
stderr.writeln('Performing safety checks');
final bool isSuperset = testIsSuperset(newTokenPairMap, oldTokenPairMap);
final bool isStable = testIsStable(newTokenPairMap, oldTokenPairMap);
if ((!isSuperset || !isStable) && argResults[_enforceSafetyChecks] as bool) {
exit(1);
}
final String iconsTemplateContents = iconsTemplateFile.readAsStringSync();
stderr.writeln("Generating icons ${argResults[_dryRunOption] as bool ? '' : 'to ${iconsFile.path}'}");
final String newIconsContents = _regenerateIconsFile(
iconsTemplateContents,
newTokenPairMap,
argResults[_fontFamilyOption] as String,
argResults[_classNameOption] as String,
argResults[_enforceSafetyChecks] as bool,
);
if (argResults[_dryRunOption] as bool) {
stdout.write(newIconsContents);
} else {
iconsFile.writeAsStringSync(newIconsContents);
final SplayTreeMap<String, String> sortedNewTokenPairMap = SplayTreeMap<String, String>.of(newTokenPairMap);
_regenerateCodepointsFile(oldCodepointsFile, sortedNewTokenPairMap);
sortedNewTokenPairMap.removeWhere((String key, String value) => oldTokenPairMap.containsKey(key));
_generateIconDemo(File(_defaultDemoFilePath), sortedNewTokenPairMap);
}
}
ArgResults _handleArguments(List<String> args) {
final ArgParser argParser = ArgParser()
..addOption(_iconsPathOption,
defaultsTo: _defaultIconsPath,
help: 'Location of the material icons file')
..addOption(_iconsTemplatePathOption,
defaultsTo: _defaultIconsPath,
help:
'Location of the material icons file template. Usually the same as --$_iconsPathOption')
..addOption(_newCodepointsPathOption,
defaultsTo: _defaultNewCodepointsPath,
help: 'Location of the new codepoints directory')
..addOption(_oldCodepointsPathOption,
defaultsTo: _defaultOldCodepointsPath,
help: 'Location of the existing codepoints directory')
..addOption(_fontFamilyOption,
defaultsTo: _defaultFontFamily,
help: 'The font family to use for the IconData constants')
..addMultiOption(_possibleStyleSuffixesOption,
defaultsTo: _defaultPossibleStyleSuffixes,
help: 'A comma-separated list of suffixes (typically an optional '
'family + a style) e.g. _outlined, _monoline_filled')
..addOption(_classNameOption,
defaultsTo: _defaultClassName,
help: 'The containing class for all icons')
..addFlag(_enforceSafetyChecks,
defaultsTo: true,
help: 'Whether to exit if safety checks fail (e.g. codepoints are missing or unstable')
..addFlag(_dryRunOption);
argParser.addFlag('help', abbr: 'h', negatable: false, callback: (bool help) {
if (help) {
print(argParser.usage);
exit(1);
}
});
return argParser.parse(args);
}
Map<String, String> stringToTokenPairMap(String codepointData) {
final Iterable<String> cleanData = LineSplitter.split(codepointData)
.map((String line) => line.trim())
.where((String line) => line.isNotEmpty);
final Map<String, String> pairs = <String, String>{};
for (final String line in cleanData) {
final List<String> tokens = line.split(' ');
if (tokens.length != 2) {
throw FormatException('Unexpected codepoint data: $line');
}
pairs.putIfAbsent(tokens[0], () => tokens[1]);
}
return pairs;
}
String _regenerateIconsFile(
String templateFileContents,
Map<String, String> tokenPairMap,
String fontFamily,
String className,
bool enforceSafetyChecks,
) {
final List<Icon> newIcons = tokenPairMap.entries
.map((MapEntry<String, String> entry) =>
Icon(entry, fontFamily: fontFamily, className: className))
.toList();
newIcons.sort((Icon a, Icon b) => a._compareTo(b));
final StringBuffer buf = StringBuffer();
bool generating = false;
for (final String line in LineSplitter.split(templateFileContents)) {
if (!generating) {
buf.writeln(line);
}
// Generate for PlatformAdaptiveIcons
if (line.contains(_beginPlatformAdaptiveGeneratedMark)) {
generating = true;
final List<String> platformAdaptiveDeclarations = <String>[];
_platformAdaptiveIdentifiers.forEach((String flutterId, List<String> ids) {
// Automatically finds and generates all icon declarations.
for (final String style in <String>['', '_outlined', '_rounded', '_sharp']) {
try {
final Icon agnosticIcon = newIcons.firstWhere(
(Icon icon) => icon.id == '${ids[0]}$style',
orElse: () => throw ids[0]);
final Icon iOSIcon = newIcons.firstWhere(
(Icon icon) => icon.id == '${ids[1]}$style',
orElse: () => throw ids[1]);
platformAdaptiveDeclarations.add(
agnosticIcon.platformAdaptiveDeclaration('$flutterId$style', iOSIcon),
);
} catch (e) {
if (style == '') {
// Throw an error for baseline icons.
stderr.writeln("❌ Platform adaptive icon '$e' not found.");
if (enforceSafetyChecks) {
stderr.writeln('Safety checks failed');
exit(1);
}
} else {
// Ignore errors for styled icons since some don't exist.
}
}
}
});
buf.write(platformAdaptiveDeclarations.join());
} else if (line.contains(_endPlatformAdaptiveGeneratedMark)) {
generating = false;
buf.writeln(line);
}
// Generate for Icons
if (line.contains(_beginGeneratedMark)) {
generating = true;
final String iconDeclarationsString = newIcons.map((Icon icon) => icon.fullDeclaration).join();
buf.write(iconDeclarationsString);
} else if (line.contains(_endGeneratedMark)) {
generating = false;
buf.writeln(line);
}
}
return buf.toString();
}
@visibleForTesting
bool testIsSuperset(Map<String, String> newCodepoints, Map<String, String> oldCodepoints) {
final Set<String> newCodepointsSet = newCodepoints.keys.toSet();
final Set<String> oldCodepointsSet = oldCodepoints.keys.toSet();
final int diff = newCodepointsSet.length - oldCodepointsSet.length;
if (diff > 0) {
stderr.writeln('🆕 $diff new codepoints: ${newCodepointsSet.difference(oldCodepointsSet)}');
}
if (!newCodepointsSet.containsAll(oldCodepointsSet)) {
stderr.writeln(
'❌ new codepoints file does not contain all ${oldCodepointsSet.length} '
'existing codepoints. Missing: ${oldCodepointsSet.difference(newCodepointsSet)}');
return false;
} else {
stderr.writeln('✅ new codepoints file contains all ${oldCodepointsSet.length} existing codepoints');
}
return true;
}
@visibleForTesting
bool testIsStable(Map<String, String> newCodepoints, Map<String, String> oldCodepoints) {
final int oldCodepointsCount = oldCodepoints.length;
final List<String> unstable = <String>[];
oldCodepoints.forEach((String key, String value) {
if (newCodepoints.containsKey(key)) {
if (value != newCodepoints[key]) {
unstable.add(key);
}
}
});
if (unstable.isNotEmpty) {
stderr.writeln('❌ out of $oldCodepointsCount existing codepoints, ${unstable.length} were unstable: $unstable');
return false;
} else {
stderr.writeln('✅ all existing $oldCodepointsCount codepoints are stable');
return true;
}
}
void _regenerateCodepointsFile(File oldCodepointsFile, Map<String, String> tokenPairMap) {
stderr.writeln('Regenerating old codepoints file ${oldCodepointsFile.path}');
final StringBuffer buf = StringBuffer();
tokenPairMap.forEach((String key, String value) => buf.writeln('$key $value'));
oldCodepointsFile.writeAsStringSync(buf.toString());
}
void _generateIconDemo(File demoFilePath, Map<String, String> tokenPairMap) {
if (tokenPairMap.isEmpty) {
stderr.writeln('No new icons, skipping generating icon demo');
return;
}
stderr.writeln('Generating icon demo at $_defaultDemoFilePath');
final StringBuffer newIconUsages = StringBuffer();
for (final MapEntry<String, String> entry in tokenPairMap.entries) {
newIconUsages.writeln(Icon(entry).usage);
}
final String demoFileContents = '''
import 'package:flutter/material.dart';
void main() => runApp(const IconDemo());
class IconDemo extends StatelessWidget {
const IconDemo({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Wrap(
children: const [
$newIconUsages
],
),
),
);
}
}
''';
demoFilePath.writeAsStringSync(demoFileContents);
}
class Icon {
// Parse tokenPair (e.g. {"6_ft_apart_outlined": "e004"}).
Icon(MapEntry<String, String> tokenPair, {
this.fontFamily = _defaultFontFamily,
this.possibleStyleSuffixes = _defaultPossibleStyleSuffixes,
this.className = _defaultClassName,
}) {
id = tokenPair.key;
hexCodepoint = tokenPair.value;
// Determine family and HTML class suffix for Dartdoc.
if (id.endsWith('_gm_outlined')) {
dartdocFamily = 'GM';
dartdocHtmlSuffix = '-outlined';
} else if (id.endsWith('_gm_filled')) {
dartdocFamily = 'GM';
dartdocHtmlSuffix = '-filled';
} else if (id.endsWith('_monoline_outlined')) {
dartdocFamily = 'Monoline';
dartdocHtmlSuffix = '-outlined';
} else if (id.endsWith('_monoline_filled')) {
dartdocFamily = 'Monoline';
dartdocHtmlSuffix = '-filled';
} else {
dartdocFamily = 'material';
if (id.endsWith('_baseline')) {
id = _removeLast(id, '_baseline');
dartdocHtmlSuffix = '';
} else if (id.endsWith('_outlined')) {
dartdocHtmlSuffix = '-outlined';
} else if (id.endsWith('_rounded')) {
dartdocHtmlSuffix = '-round';
} else if (id.endsWith('_sharp')) {
dartdocHtmlSuffix = '-sharp';
}
}
_generateShortId();
_generateFlutterId();
}
late String id; // e.g. 5g, 5g_outlined, 5g_rounded, 5g_sharp
late String shortId; // e.g. 5g
late String flutterId; // e.g. five_g, five_g_outlined, five_g_rounded, five_g_sharp
late String hexCodepoint; // e.g. e547
late String dartdocFamily; // e.g. material
late String dartdocHtmlSuffix = ''; // The suffix for the 'material-icons' HTML class.
String fontFamily; // The IconData font family.
List<String> possibleStyleSuffixes; // A list of possible suffixes e.g. _outlined, _monoline_filled.
String className; // The containing class.
String get name => shortId.replaceAll('_', ' ').trim();
String get style => dartdocHtmlSuffix == '' ? '' : ' (${dartdocHtmlSuffix.replaceFirst('-', '')})';
String get dartDoc =>
'<i class="material-icons$dartdocHtmlSuffix md-36">$shortId</i> — $dartdocFamily icon named "$name"$style';
String get usage => 'Icon($className.$flutterId),';
bool get isMirroredInRTL {
// Remove common suffixes (e.g. "_new" or "_alt") from the shortId.
final String normalizedShortId = shortId.replaceAll(RegExp(r'_(new|alt|off|on)$'), '');
return _iconsMirroredWhenRTL.any((String shortIdMirroredWhenRTL) => normalizedShortId == shortIdMirroredWhenRTL);
}
String get declaration =>
"static const IconData $flutterId = IconData(0x$hexCodepoint, fontFamily: '$fontFamily'${isMirroredInRTL ? ', matchTextDirection: true' : ''});";
String get fullDeclaration => '''
/// $dartDoc.
$declaration
''';
String platformAdaptiveDeclaration(String fullFlutterId, Icon iOSIcon) => '''
/// Platform-adaptive icon for $dartDoc and ${iOSIcon.dartDoc}.;
IconData get $fullFlutterId => !_isCupertino() ? $className.$flutterId : $className.${iOSIcon.flutterId};
''';
@override
String toString() => id;
/// Analogous to [String.compareTo]
int _compareTo(Icon b) {
if (shortId == b.shortId) {
// Sort a regular icon before its variants.
return id.length - b.id.length;
}
return shortId.compareTo(b.shortId);
}
static String _removeLast(String string, String toReplace) {
return string.replaceAll(RegExp('$toReplace\$'), '');
}
/// See [shortId].
void _generateShortId() {
shortId = id;
for (final String styleSuffix in possibleStyleSuffixes) {
shortId = _removeLast(shortId, styleSuffix);
if (shortId != id) {
break;
}
}
}
/// See [flutterId].
void _generateFlutterId() {
flutterId = id;
// Exact identifier rewrites.
for (final MapEntry<String, String> rewritePair in _identifierExactRewrites.entries) {
if (shortId == rewritePair.key) {
flutterId = id.replaceFirst(
rewritePair.key,
_identifierExactRewrites[rewritePair.key]!,
);
}
}
// Prefix identifier rewrites.
for (final MapEntry<String, String> rewritePair in _identifierPrefixRewrites.entries) {
if (id.startsWith(rewritePair.key)) {
flutterId = id.replaceFirst(
rewritePair.key,
_identifierPrefixRewrites[rewritePair.key]!,
);
}
}
// Prevent double underscores.
flutterId = flutterId.replaceAll('__', '_');
}
}
| flutter/dev/tools/update_icons.dart/0 | {
"file_path": "flutter/dev/tools/update_icons.dart",
"repo_id": "flutter",
"token_count": 7641
} | 561 |
<svg id="svg_build_00" xmlns="http://www.w3.org/2000/svg" width="48px" height="48px" >
<path id="path_1" d="M 0,19.0 l 48.0, 0.0 l 0.0, 10.0 l -48.0, 0.0 Z " fill="#000000" />
</svg>
| flutter/dev/tools/vitool/test_assets/horizontal_bar_relative.svg/0 | {
"file_path": "flutter/dev/tools/vitool/test_assets/horizontal_bar_relative.svg",
"repo_id": "flutter",
"token_count": 95
} | 562 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'common.dart';
final Set<String> interestingLabels = <String>{
'$Row',
'$TestRoot',
'$TestChildWidget',
'$Container',
};
void main() {
ZoneIgnoringTestBinding.ensureInitialized();
initTimelineTests();
test('Children of MultiChildRenderObjectElement show up in tracing', () async {
// We don't have expectations around the first frame because there's a race around
// the warm-up frame that we don't want to get involved in here.
await runFrame(() { runApp(const TestRoot()); });
await SchedulerBinding.instance.endOfFrame;
await fetchInterestingEvents(interestingLabels);
debugProfileBuildsEnabled = true;
await runFrame(() {
TestRoot.state.showRow();
});
expect(
await fetchInterestingEventNames(interestingLabels),
<String>['TestRoot', 'Row', 'TestChildWidget', 'Container', 'TestChildWidget', 'Container'],
);
debugProfileBuildsEnabled = false;
}, skip: isBrowser); // [intended] uses dart:isolate and io.
}
class TestRoot extends StatefulWidget {
const TestRoot({super.key});
static late TestRootState state;
@override
State<TestRoot> createState() => TestRootState();
}
class TestRootState extends State<TestRoot> {
@override
void initState() {
super.initState();
TestRoot.state = this;
}
bool _showRow = false;
void showRow() {
setState(() {
_showRow = true;
});
}
@override
Widget build(BuildContext context) {
return _showRow
? const Row(
children: <Widget>[
TestChildWidget(),
TestChildWidget(),
],
)
: Container();
}
}
class TestChildWidget extends StatelessWidget {
const TestChildWidget({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
| flutter/dev/tracing_tests/test/inflate_widget_tracing_test.dart/0 | {
"file_path": "flutter/dev/tracing_tests/test/inflate_widget_tracing_test.dart",
"repo_id": "flutter",
"token_count": 723
} | 563 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [Curve2D].
void main() => runApp(const Curve2DExampleApp());
class Curve2DExampleApp extends StatelessWidget {
const Curve2DExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Curve2DExample(),
);
}
}
// This is the path that the child will follow. It's a CatmullRomSpline so
// that the coordinates can be specified that it must pass through. If the
// tension is set to 1.0, it will linearly interpolate between those points,
// instead of interpolating smoothly.
final CatmullRomSpline path = CatmullRomSpline(
const <Offset>[
Offset(0.05, 0.75),
Offset(0.18, 0.23),
Offset(0.32, 0.04),
Offset(0.73, 0.5),
Offset(0.42, 0.74),
Offset(0.73, 0.01),
Offset(0.93, 0.93),
Offset(0.05, 0.75),
],
startHandle: const Offset(0.93, 0.93),
endHandle: const Offset(0.18, 0.23),
);
class FollowCurve2D extends StatefulWidget {
const FollowCurve2D({
super.key,
required this.path,
this.curve = Curves.easeInOut,
required this.child,
this.duration = const Duration(seconds: 1),
});
final Curve2D path;
final Curve curve;
final Duration duration;
final Widget child;
@override
State<FollowCurve2D> createState() => _FollowCurve2DState();
}
class _FollowCurve2DState extends State<FollowCurve2D> with TickerProviderStateMixin {
// The animation controller for this animation.
late AnimationController controller;
// The animation that will be used to apply the widget's animation curve.
late Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(duration: widget.duration, vsync: this);
animation = CurvedAnimation(parent: controller, curve: widget.curve);
// Have the controller repeat indefinitely. If you want it to "bounce" back
// and forth, set the reverse parameter to true.
controller.repeat();
controller.addListener(() => setState(() {}));
}
@override
void dispose() {
// Always have to dispose of animation controllers when done.
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Scale the path values to match the -1.0 to 1.0 domain of the Alignment widget.
final Offset position = widget.path.transform(animation.value) * 2.0 - const Offset(1.0, 1.0);
return Align(
alignment: Alignment(position.dx, position.dy),
child: widget.child,
);
}
}
class Curve2DExample extends StatelessWidget {
const Curve2DExample({super.key});
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
alignment: Alignment.center,
child: FollowCurve2D(
path: path,
duration: const Duration(seconds: 3),
child: CircleAvatar(
backgroundColor: Colors.yellow,
child: DefaultTextStyle(
style: Theme.of(context).textTheme.titleLarge!,
child: const Text('B'), // Buzz, buzz!
),
),
),
);
}
}
| flutter/examples/api/lib/animation/curves/curve2_d.0.dart/0 | {
"file_path": "flutter/examples/api/lib/animation/curves/curve2_d.0.dart",
"repo_id": "flutter",
"token_count": 1168
} | 564 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
/// Flutter code sample for [CupertinoPicker].
const double _kItemExtent = 32.0;
const List<String> _fruitNames = <String>[
'Apple',
'Mango',
'Banana',
'Orange',
'Pineapple',
'Strawberry',
];
void main() => runApp(const CupertinoPickerApp());
class CupertinoPickerApp extends StatelessWidget {
const CupertinoPickerApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: CupertinoPickerExample(),
);
}
}
class CupertinoPickerExample extends StatefulWidget {
const CupertinoPickerExample({super.key});
@override
State<CupertinoPickerExample> createState() => _CupertinoPickerExampleState();
}
class _CupertinoPickerExampleState extends State<CupertinoPickerExample> {
int _selectedFruit = 0;
// This shows a CupertinoModalPopup with a reasonable fixed height which hosts CupertinoPicker.
void _showDialog(Widget child) {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) => Container(
height: 216,
padding: const EdgeInsets.only(top: 6.0),
// The Bottom margin is provided to align the popup above the system navigation bar.
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
// Provide a background color for the popup.
color: CupertinoColors.systemBackground.resolveFrom(context),
// Use a SafeArea widget to avoid system overlaps.
child: SafeArea(
top: false,
child: child,
),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('CupertinoPicker Sample'),
),
child: DefaultTextStyle(
style: TextStyle(
color: CupertinoColors.label.resolveFrom(context),
fontSize: 22.0,
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Selected fruit: '),
CupertinoButton(
padding: EdgeInsets.zero,
// Display a CupertinoPicker with list of fruits.
onPressed: () => _showDialog(
CupertinoPicker(
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
itemExtent: _kItemExtent,
// This sets the initial item.
scrollController: FixedExtentScrollController(
initialItem: _selectedFruit,
),
// This is called when selected item is changed.
onSelectedItemChanged: (int selectedItem) {
setState(() {
_selectedFruit = selectedItem;
});
},
children: List<Widget>.generate(_fruitNames.length, (int index) {
return Center(child: Text(_fruitNames[index]));
}),
),
),
// This displays the selected fruit name.
child: Text(
_fruitNames[_selectedFruit],
style: const TextStyle(
fontSize: 22.0,
),
),
),
],
),
),
),
);
}
}
| flutter/examples/api/lib/cupertino/picker/cupertino_picker.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/picker/cupertino_picker.0.dart",
"repo_id": "flutter",
"token_count": 1758
} | 565 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
/// Flutter code sample for [CupertinoTextField].
void main() => runApp(const CupertinoTextFieldApp());
class CupertinoTextFieldApp extends StatelessWidget {
const CupertinoTextFieldApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: CupertinoTextFieldExample(),
);
}
}
class CupertinoTextFieldExample extends StatefulWidget {
const CupertinoTextFieldExample({super.key});
@override
State<CupertinoTextFieldExample> createState() => _CupertinoTextFieldExampleState();
}
class _CupertinoTextFieldExampleState extends State<CupertinoTextFieldExample> {
late TextEditingController _textController;
@override
void initState() {
super.initState();
_textController = TextEditingController(text: 'initial text');
}
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('CupertinoTextField Sample'),
),
child: Center(
child: CupertinoTextField(
controller: _textController,
),
),
);
}
}
| flutter/examples/api/lib/cupertino/text_field/cupertino_text_field.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/text_field/cupertino_text_field.0.dart",
"repo_id": "flutter",
"token_count": 500
} | 566 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ColorScheme.fromImageProvider] with content-based dynamic color.
const Widget divider = SizedBox(height: 10);
const double narrowScreenWidthThreshold = 400;
void main() => runApp(DynamicColorExample());
class DynamicColorExample extends StatefulWidget {
DynamicColorExample({super.key});
final List<ImageProvider> images = <NetworkImage>[
const NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png'),
const NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_2.png'),
const NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_3.png'),
const NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_4.png'),
const NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_5.png'),
const NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_6.png'),
];
@override
State<DynamicColorExample> createState() => _DynamicColorExampleState();
}
class _DynamicColorExampleState extends State<DynamicColorExample> {
late ColorScheme currentColorScheme;
String currentHyperlinkImage = '';
late int selectedImage;
late bool isLight;
late bool isLoading;
@override
void initState() {
super.initState();
selectedImage = 0;
isLight = true;
isLoading = true;
currentColorScheme = const ColorScheme.light();
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateImage(widget.images[selectedImage]);
isLoading = false;
});
}
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = currentColorScheme;
final Color selectedColor = currentColorScheme.primary;
final ThemeData lightTheme = ThemeData(
colorSchemeSeed: selectedColor,
brightness: Brightness.light,
useMaterial3: false,
);
final ThemeData darkTheme = ThemeData(
colorSchemeSeed: selectedColor,
brightness: Brightness.dark,
useMaterial3: false,
);
Widget schemeLabel(String brightness, ColorScheme colorScheme) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 15),
child: Text(
brightness,
style: TextStyle(fontWeight: FontWeight.bold, color: colorScheme.onSecondaryContainer),
),
);
}
Widget schemeView(ThemeData theme) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: ColorSchemeView(colorScheme: theme.colorScheme),
);
}
return MaterialApp(
theme: ThemeData(useMaterial3: true, colorScheme: colorScheme),
debugShowCheckedModeBanner: false,
home: Builder(
builder: (BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Content Based Dynamic Color'),
backgroundColor: colorScheme.primary,
foregroundColor: colorScheme.onPrimary,
actions: <Widget>[
const Icon(Icons.light_mode),
Switch(
activeColor: colorScheme.primary,
activeTrackColor: colorScheme.surface,
inactiveTrackColor: colorScheme.onSecondary,
value: isLight,
onChanged: (bool value) {
setState(() {
isLight = value;
_updateImage(widget.images[selectedImage]);
});
})
],
),
body: Center(
child: isLoading
? const CircularProgressIndicator()
: ColoredBox(
color: colorScheme.secondaryContainer,
child: Column(
children: <Widget>[
divider,
_imagesRow(
context,
widget.images,
colorScheme,
),
divider,
Expanded(
child: ColoredBox(
color: colorScheme.surface,
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth < narrowScreenWidthThreshold) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
divider,
schemeLabel('Light ColorScheme', colorScheme),
schemeView(lightTheme),
divider,
divider,
schemeLabel('Dark ColorScheme', colorScheme),
schemeView(darkTheme),
],
),
);
} else {
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(top: 5),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Column(
children: <Widget>[
schemeLabel('Light ColorScheme', colorScheme),
schemeView(lightTheme),
],
),
),
Expanded(
child: Column(
children: <Widget>[
schemeLabel('Dark ColorScheme', colorScheme),
schemeView(darkTheme),
],
),
),
],
),
],
),
),
);
}
}),
),
),
],
),
),
),
),
),
);
}
Future<void> _updateImage(ImageProvider provider) async {
final ColorScheme newColorScheme = await ColorScheme.fromImageProvider(
provider: provider, brightness: isLight ? Brightness.light : Brightness.dark);
if (!mounted) {
return;
}
setState(() {
selectedImage = widget.images.indexOf(provider);
currentColorScheme = newColorScheme;
});
}
// For small screens, have two rows of image selection. For wide screens,
// fit them onto one row.
Widget _imagesRow(BuildContext context, List<ImageProvider> images, ColorScheme colorScheme) {
final double windowHeight = MediaQuery.of(context).size.height;
final double windowWidth = MediaQuery.of(context).size.width;
return Padding(
padding: const EdgeInsets.all(8.0),
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth > 800) {
return _adaptiveLayoutImagesRow(images, colorScheme, windowHeight);
} else {
return Column(children: <Widget>[
_adaptiveLayoutImagesRow(images.sublist(0, 3), colorScheme, windowWidth),
_adaptiveLayoutImagesRow(images.sublist(3), colorScheme, windowWidth),
]);
}
}),
);
}
Widget _adaptiveLayoutImagesRow(List<ImageProvider> images, ColorScheme colorScheme, double windowWidth) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: images
.map(
(ImageProvider image) => Flexible(
flex: (images.length / 3).floor(),
child: GestureDetector(
onTap: () => _updateImage(image),
child: Card(
color: widget.images.indexOf(image) == selectedImage
? colorScheme.primaryContainer
: colorScheme.surface,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: windowWidth * .25),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image(image: image),
),
),
),
),
),
),
)
.toList(),
);
}
}
class ColorSchemeView extends StatelessWidget {
const ColorSchemeView({super.key, required this.colorScheme});
final ColorScheme colorScheme;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ColorGroup(children: <ColorChip>[
ColorChip(label: 'primary', color: colorScheme.primary, onColor: colorScheme.onPrimary),
ColorChip(label: 'onPrimary', color: colorScheme.onPrimary, onColor: colorScheme.primary),
ColorChip(
label: 'primaryContainer', color: colorScheme.primaryContainer, onColor: colorScheme.onPrimaryContainer),
ColorChip(
label: 'onPrimaryContainer',
color: colorScheme.onPrimaryContainer,
onColor: colorScheme.primaryContainer),
]),
divider,
ColorGroup(children: <ColorChip>[
ColorChip(label: 'secondary', color: colorScheme.secondary, onColor: colorScheme.onSecondary),
ColorChip(label: 'onSecondary', color: colorScheme.onSecondary, onColor: colorScheme.secondary),
ColorChip(
label: 'secondaryContainer',
color: colorScheme.secondaryContainer,
onColor: colorScheme.onSecondaryContainer),
ColorChip(
label: 'onSecondaryContainer',
color: colorScheme.onSecondaryContainer,
onColor: colorScheme.secondaryContainer),
]),
divider,
ColorGroup(
children: <ColorChip>[
ColorChip(label: 'tertiary', color: colorScheme.tertiary, onColor: colorScheme.onTertiary),
ColorChip(label: 'onTertiary', color: colorScheme.onTertiary, onColor: colorScheme.tertiary),
ColorChip(
label: 'tertiaryContainer',
color: colorScheme.tertiaryContainer,
onColor: colorScheme.onTertiaryContainer),
ColorChip(
label: 'onTertiaryContainer',
color: colorScheme.onTertiaryContainer,
onColor: colorScheme.tertiaryContainer),
],
),
divider,
ColorGroup(
children: <ColorChip>[
ColorChip(label: 'error', color: colorScheme.error, onColor: colorScheme.onError),
ColorChip(label: 'onError', color: colorScheme.onError, onColor: colorScheme.error),
ColorChip(
label: 'errorContainer', color: colorScheme.errorContainer, onColor: colorScheme.onErrorContainer),
ColorChip(
label: 'onErrorContainer', color: colorScheme.onErrorContainer, onColor: colorScheme.errorContainer),
],
),
divider,
ColorGroup(
children: <ColorChip>[
ColorChip(label: 'surface', color: colorScheme.surface, onColor: colorScheme.onSurface),
ColorChip(label: 'onSurface', color: colorScheme.onSurface, onColor: colorScheme.surface),
ColorChip(
label: 'onSurfaceVariant', color: colorScheme.onSurfaceVariant, onColor: colorScheme.surfaceContainerHighest),
],
),
divider,
ColorGroup(
children: <ColorChip>[
ColorChip(label: 'outline', color: colorScheme.outline),
ColorChip(label: 'shadow', color: colorScheme.shadow),
ColorChip(
label: 'inverseSurface', color: colorScheme.inverseSurface, onColor: colorScheme.onInverseSurface),
ColorChip(
label: 'onInverseSurface', color: colorScheme.onInverseSurface, onColor: colorScheme.inverseSurface),
ColorChip(label: 'inversePrimary', color: colorScheme.inversePrimary, onColor: colorScheme.primary),
],
),
],
);
}
}
class ColorGroup extends StatelessWidget {
const ColorGroup({super.key, required this.children});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return RepaintBoundary(
child: Card(clipBehavior: Clip.antiAlias, child: Column(children: children)),
);
}
}
class ColorChip extends StatelessWidget {
const ColorChip({
super.key,
required this.color,
required this.label,
this.onColor,
});
final Color color;
final Color? onColor;
final String label;
static Color contrastColor(Color color) {
final Brightness brightness = ThemeData.estimateBrightnessForColor(color);
return switch (brightness) {
Brightness.dark => Colors.white,
Brightness.light => Colors.black,
};
}
@override
Widget build(BuildContext context) {
final Color labelColor = onColor ?? contrastColor(color);
return ColoredBox(
color: color,
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: <Expanded>[
Expanded(child: Text(label, style: TextStyle(color: labelColor))),
],
),
),
);
}
}
| flutter/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/color_scheme/dynamic_content_color.0.dart",
"repo_id": "flutter",
"token_count": 7432
} | 567 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ExpansionTile].
void main() => runApp(const ExpansionTileApp());
class ExpansionTileApp extends StatelessWidget {
const ExpansionTileApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('ExpansionTile Sample')),
body: const ExpansionTileExample(),
),
);
}
}
class ExpansionTileExample extends StatefulWidget {
const ExpansionTileExample({super.key});
@override
State<ExpansionTileExample> createState() => _ExpansionTileExampleState();
}
class _ExpansionTileExampleState extends State<ExpansionTileExample> {
bool _customTileExpanded = false;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
const ExpansionTile(
title: Text('ExpansionTile 1'),
subtitle: Text('Trailing expansion arrow icon'),
children: <Widget>[
ListTile(title: Text('This is tile number 1')),
],
),
ExpansionTile(
title: const Text('ExpansionTile 2'),
subtitle: const Text('Custom expansion arrow icon'),
trailing: Icon(
_customTileExpanded ? Icons.arrow_drop_down_circle : Icons.arrow_drop_down,
),
children: const <Widget>[
ListTile(title: Text('This is tile number 2')),
],
onExpansionChanged: (bool expanded) {
setState(() {
_customTileExpanded = expanded;
});
},
),
const ExpansionTile(
title: Text('ExpansionTile 3'),
subtitle: Text('Leading expansion arrow icon'),
controlAffinity: ListTileControlAffinity.leading,
children: <Widget>[
ListTile(title: Text('This is tile number 3')),
],
),
],
);
}
}
| flutter/examples/api/lib/material/expansion_tile/expansion_tile.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/expansion_tile/expansion_tile.0.dart",
"repo_id": "flutter",
"token_count": 848
} | 568 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [InkWell].
void main() => runApp(const InkWellExampleApp());
class InkWellExampleApp extends StatelessWidget {
const InkWellExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('InkWell Sample')),
body: const Center(
child: InkWellExample(),
),
),
);
}
}
class InkWellExample extends StatefulWidget {
const InkWellExample({super.key});
@override
State<InkWellExample> createState() => _InkWellExampleState();
}
class _InkWellExampleState extends State<InkWellExample> {
double sideLength = 50;
@override
Widget build(BuildContext context) {
return AnimatedContainer(
height: sideLength,
width: sideLength,
duration: const Duration(seconds: 2),
curve: Curves.easeIn,
child: Material(
color: Colors.yellow,
child: InkWell(
onTap: () {
setState(() {
sideLength == 50 ? sideLength = 100 : sideLength = 50;
});
},
),
),
);
}
}
| flutter/examples/api/lib/material/ink_well/ink_well.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/ink_well/ink_well.0.dart",
"repo_id": "flutter",
"token_count": 522
} | 569 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [InputDecoration.suffixIconConstraints].
void main() => runApp(const SuffixIconConstraintsExampleApp());
class SuffixIconConstraintsExampleApp extends StatelessWidget {
const SuffixIconConstraintsExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('InputDecoration Sample')),
body: const SuffixIconConstraintsExample(),
),
);
}
}
class SuffixIconConstraintsExample extends StatelessWidget {
const SuffixIconConstraintsExample({super.key});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
decoration: InputDecoration(
hintText: 'Normal Icon Constraints',
suffixIcon: Icon(Icons.search),
),
),
SizedBox(height: 10),
TextField(
decoration: InputDecoration(
isDense: true,
hintText: 'Smaller Icon Constraints',
suffixIcon: Icon(Icons.search),
suffixIconConstraints: BoxConstraints(
minHeight: 32,
minWidth: 32,
),
),
),
],
),
);
}
}
| flutter/examples/api/lib/material/input_decorator/input_decoration.suffix_icon_constraints.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/input_decorator/input_decoration.suffix_icon_constraints.0.dart",
"repo_id": "flutter",
"token_count": 716
} | 570 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [MenuAnchor].
void main() => runApp(const ContextMenuApp());
/// An enhanced enum to define the available menus and their shortcuts.
///
/// Using an enum for menu definition is not required, but this illustrates how
/// they could be used for simple menu systems.
enum MenuEntry {
about('About'),
showMessage('Show Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
hideMessage('Hide Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
colorMenu('Color Menu'),
colorRed('Red Background', SingleActivator(LogicalKeyboardKey.keyR, control: true)),
colorGreen('Green Background', SingleActivator(LogicalKeyboardKey.keyG, control: true)),
colorBlue('Blue Background', SingleActivator(LogicalKeyboardKey.keyB, control: true));
const MenuEntry(this.label, [this.shortcut]);
final String label;
final MenuSerializableShortcut? shortcut;
}
class MyContextMenu extends StatefulWidget {
const MyContextMenu({super.key, required this.message});
final String message;
@override
State<MyContextMenu> createState() => _MyContextMenuState();
}
class _MyContextMenuState extends State<MyContextMenu> {
MenuEntry? _lastSelection;
final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button');
final MenuController _menuController = MenuController();
ShortcutRegistryEntry? _shortcutsEntry;
bool _menuWasEnabled = false;
Color get backgroundColor => _backgroundColor;
Color _backgroundColor = Colors.red;
set backgroundColor(Color value) {
if (_backgroundColor != value) {
setState(() {
_backgroundColor = value;
});
}
}
bool get showingMessage => _showingMessage;
bool _showingMessage = false;
set showingMessage(bool value) {
if (_showingMessage != value) {
setState(() {
_showingMessage = value;
});
}
}
@override
void initState() {
super.initState();
_disableContextMenu();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Dispose of any previously registered shortcuts, since they are about to
// be replaced.
_shortcutsEntry?.dispose();
// Collect the shortcuts from the different menu selections so that they can
// be registered to apply to the entire app. Menus don't register their
// shortcuts, they only display the shortcut hint text.
final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{
for (final MenuEntry item in MenuEntry.values)
if (item.shortcut != null) item.shortcut!: VoidCallbackIntent(() => _activate(item)),
};
// Register the shortcuts with the ShortcutRegistry so that they are
// available to the entire application.
_shortcutsEntry = ShortcutRegistry.of(context).addAll(shortcuts);
}
@override
void dispose() {
_shortcutsEntry?.dispose();
_buttonFocusNode.dispose();
_reenableContextMenu();
super.dispose();
}
Future<void> _disableContextMenu() async {
if (!kIsWeb) {
// Does nothing on non-web platforms.
return;
}
_menuWasEnabled = BrowserContextMenu.enabled;
if (_menuWasEnabled) {
await BrowserContextMenu.disableContextMenu();
}
}
void _reenableContextMenu() {
if (!kIsWeb) {
// Does nothing on non-web platforms.
return;
}
if (_menuWasEnabled && !BrowserContextMenu.enabled) {
BrowserContextMenu.enableContextMenu();
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(50),
child: GestureDetector(
onTapDown: _handleTapDown,
onSecondaryTapDown: _handleSecondaryTapDown,
child: MenuAnchor(
controller: _menuController,
menuChildren: <Widget>[
MenuItemButton(
child: Text(MenuEntry.about.label),
onPressed: () => _activate(MenuEntry.about),
),
if (_showingMessage)
MenuItemButton(
onPressed: () => _activate(MenuEntry.hideMessage),
shortcut: MenuEntry.hideMessage.shortcut,
child: Text(MenuEntry.hideMessage.label),
),
if (!_showingMessage)
MenuItemButton(
onPressed: () => _activate(MenuEntry.showMessage),
shortcut: MenuEntry.showMessage.shortcut,
child: Text(MenuEntry.showMessage.label),
),
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
onPressed: () => _activate(MenuEntry.colorRed),
shortcut: MenuEntry.colorRed.shortcut,
child: Text(MenuEntry.colorRed.label),
),
MenuItemButton(
onPressed: () => _activate(MenuEntry.colorGreen),
shortcut: MenuEntry.colorGreen.shortcut,
child: Text(MenuEntry.colorGreen.label),
),
MenuItemButton(
onPressed: () => _activate(MenuEntry.colorBlue),
shortcut: MenuEntry.colorBlue.shortcut,
child: Text(MenuEntry.colorBlue.label),
),
],
child: const Text('Background Color'),
),
],
child: Container(
alignment: Alignment.center,
color: backgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.all(8.0),
child: Text('Right-click anywhere on the background to show the menu.'),
),
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
showingMessage ? widget.message : '',
style: Theme.of(context).textTheme.headlineSmall,
),
),
Text(_lastSelection != null ? 'Last Selected: ${_lastSelection!.label}' : ''),
],
),
),
),
),
);
}
void _activate(MenuEntry selection) {
setState(() {
_lastSelection = selection;
});
switch (selection) {
case MenuEntry.about:
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
case MenuEntry.showMessage:
case MenuEntry.hideMessage:
showingMessage = !showingMessage;
case MenuEntry.colorMenu:
break;
case MenuEntry.colorRed:
backgroundColor = Colors.red;
case MenuEntry.colorGreen:
backgroundColor = Colors.green;
case MenuEntry.colorBlue:
backgroundColor = Colors.blue;
}
}
void _handleSecondaryTapDown(TapDownDetails details) {
_menuController.open(position: details.localPosition);
}
void _handleTapDown(TapDownDetails details) {
if (_menuController.isOpen) {
_menuController.close();
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
// Don't open the menu on these platforms with a Ctrl-tap (or a
// tap).
break;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
// Only open the menu on these platforms if the control button is down
// when the tap occurs.
if (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.controlLeft) ||
HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.controlRight)) {
_menuController.open(position: details.localPosition);
}
}
}
}
class ContextMenuApp extends StatelessWidget {
const ContextMenuApp({super.key});
static const String kMessage = '"Talk less. Smile more." - A. Burr';
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const Scaffold(body: MyContextMenu(message: kMessage)),
);
}
}
| flutter/examples/api/lib/material/menu_anchor/menu_anchor.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/menu_anchor/menu_anchor.1.dart",
"repo_id": "flutter",
"token_count": 3425
} | 571 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// THIS SAMPLE ONLY WORKS ON MACOS.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [PlatformMenuBar].
void main() => runApp(const ExampleApp());
enum MenuSelection {
about,
showMessage,
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: PlatformMenuBarExample()),
);
}
}
class PlatformMenuBarExample extends StatefulWidget {
const PlatformMenuBarExample({super.key});
@override
State<PlatformMenuBarExample> createState() => _PlatformMenuBarExampleState();
}
class _PlatformMenuBarExampleState extends State<PlatformMenuBarExample> {
String _message = 'Hello';
bool _showMessage = false;
void _handleMenuSelection(MenuSelection value) {
switch (value) {
case MenuSelection.about:
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
case MenuSelection.showMessage:
setState(() {
_showMessage = !_showMessage;
});
}
}
@override
Widget build(BuildContext context) {
////////////////////////////////////
// THIS SAMPLE ONLY WORKS ON MACOS.
////////////////////////////////////
// This builds a menu hierarchy that looks like this:
// Flutter API Sample
// ├ About
// ├ ──────── (group divider)
// ├ Hide/Show Message
// ├ Messages
// │ ├ I am not throwing away my shot.
// │ └ There's a million things I haven't done, but just you wait.
// └ Quit
return PlatformMenuBar(
menus: <PlatformMenuItem>[
PlatformMenu(
label: 'Flutter API Sample',
menus: <PlatformMenuItem>[
PlatformMenuItemGroup(
members: <PlatformMenuItem>[
PlatformMenuItem(
label: 'About',
onSelected: () {
_handleMenuSelection(MenuSelection.about);
},
),
],
),
PlatformMenuItemGroup(
members: <PlatformMenuItem>[
PlatformMenuItem(
onSelected: () {
_handleMenuSelection(MenuSelection.showMessage);
},
shortcut: const CharacterActivator('m'),
label: _showMessage ? 'Hide Message' : 'Show Message',
),
PlatformMenu(
label: 'Messages',
menus: <PlatformMenuItem>[
PlatformMenuItem(
label: 'I am not throwing away my shot.',
shortcut: const SingleActivator(LogicalKeyboardKey.digit1, meta: true),
onSelected: () {
setState(() {
_message = 'I am not throwing away my shot.';
});
},
),
PlatformMenuItem(
label: "There's a million things I haven't done, but just you wait.",
shortcut: const SingleActivator(LogicalKeyboardKey.digit2, meta: true),
onSelected: () {
setState(() {
_message = "There's a million things I haven't done, but just you wait.";
});
},
),
],
),
],
),
if (PlatformProvidedMenuItem.hasMenu(PlatformProvidedMenuItemType.quit))
const PlatformProvidedMenuItem(type: PlatformProvidedMenuItemType.quit),
],
),
],
child: Center(
child: Text(_showMessage
? _message
: 'This space intentionally left blank.\n'
'Show a message here using the menu.'),
),
);
}
}
| flutter/examples/api/lib/material/platform_menu_bar/platform_menu_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/platform_menu_bar/platform_menu_bar.0.dart",
"repo_id": "flutter",
"token_count": 1976
} | 572 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [RefreshIndicator].
void main() => runApp(const RefreshIndicatorExampleApp());
class RefreshIndicatorExampleApp extends StatelessWidget {
const RefreshIndicatorExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: RefreshIndicatorExample(),
);
}
}
class RefreshIndicatorExample extends StatefulWidget {
const RefreshIndicatorExample({super.key});
@override
State<RefreshIndicatorExample> createState() => _RefreshIndicatorExampleState();
}
class _RefreshIndicatorExampleState extends State<RefreshIndicatorExample> {
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('RefreshIndicator Sample'),
),
body: RefreshIndicator(
key: _refreshIndicatorKey,
color: Colors.white,
backgroundColor: Colors.blue,
strokeWidth: 4.0,
onRefresh: () async {
// Replace this delay with the code to be executed during refresh
// and return a Future when code finishes execution.
return Future<void>.delayed(const Duration(seconds: 3));
},
// Pull from top to show refresh indicator.
child: ListView.builder(
itemCount: 25,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text('Item $index'),
);
},
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
// Show refresh indicator programmatically on button tap.
_refreshIndicatorKey.currentState?.show();
},
icon: const Icon(Icons.refresh),
label: const Text('Show Indicator'),
),
);
}
}
| flutter/examples/api/lib/material/refresh_indicator/refresh_indicator.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/refresh_indicator/refresh_indicator.0.dart",
"repo_id": "flutter",
"token_count": 771
} | 573 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ScaffoldMessenger.of].
void main() => runApp(const OfExampleApp());
class OfExampleApp extends StatefulWidget {
const OfExampleApp({super.key});
@override
State<OfExampleApp> createState() => _OfExampleAppState();
}
class _OfExampleAppState extends State<OfExampleApp> {
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
if (_counter % 10 == 0) {
_scaffoldMessengerKey.currentState!.showSnackBar(const SnackBar(
content: Text('A multiple of ten!'),
));
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: _scaffoldMessengerKey,
home: Scaffold(
appBar: AppBar(title: const Text('ScaffoldMessenger Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
);
}
}
| flutter/examples/api/lib/material/scaffold/scaffold_messenger.of.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/scaffold/scaffold_messenger.of.1.dart",
"repo_id": "flutter",
"token_count": 718
} | 574 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// Flutter code sample for [SelectableRegion].
void main() => runApp(const SelectableRegionExampleApp());
class SelectableRegionExampleApp extends StatelessWidget {
const SelectableRegionExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SelectionArea(
child: Scaffold(
appBar: AppBar(title: const Text('SelectableRegion Sample')),
body: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Select this icon', style: TextStyle(fontSize: 30)),
SizedBox(height: 10),
MySelectableAdapter(child: Icon(Icons.key, size: 30)),
],
),
),
),
),
);
}
}
class MySelectableAdapter extends StatelessWidget {
const MySelectableAdapter({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
final SelectionRegistrar? registrar = SelectionContainer.maybeOf(context);
if (registrar == null) {
return child;
}
return MouseRegion(
cursor: SystemMouseCursors.text,
child: _SelectableAdapter(
registrar: registrar,
child: child,
),
);
}
}
class _SelectableAdapter extends SingleChildRenderObjectWidget {
const _SelectableAdapter({
required this.registrar,
required Widget child,
}) : super(child: child);
final SelectionRegistrar registrar;
@override
_RenderSelectableAdapter createRenderObject(BuildContext context) {
return _RenderSelectableAdapter(
DefaultSelectionStyle.of(context).selectionColor!,
registrar,
);
}
@override
void updateRenderObject(BuildContext context, _RenderSelectableAdapter renderObject) {
renderObject
..selectionColor = DefaultSelectionStyle.of(context).selectionColor!
..registrar = registrar;
}
}
class _RenderSelectableAdapter extends RenderProxyBox with Selectable, SelectionRegistrant {
_RenderSelectableAdapter(
Color selectionColor,
SelectionRegistrar registrar,
) : _selectionColor = selectionColor,
_geometry = ValueNotifier<SelectionGeometry>(_noSelection) {
this.registrar = registrar;
_geometry.addListener(markNeedsPaint);
}
static const SelectionGeometry _noSelection = SelectionGeometry(status: SelectionStatus.none, hasContent: true);
final ValueNotifier<SelectionGeometry> _geometry;
Color get selectionColor => _selectionColor;
late Color _selectionColor;
set selectionColor(Color value) {
if (_selectionColor == value) {
return;
}
_selectionColor = value;
markNeedsPaint();
}
// ValueListenable APIs
@override
void addListener(VoidCallback listener) => _geometry.addListener(listener);
@override
void removeListener(VoidCallback listener) => _geometry.removeListener(listener);
@override
SelectionGeometry get value => _geometry.value;
// Selectable APIs.
@override
List<Rect> get boundingBoxes => <Rect>[paintBounds];
// Adjust this value to enlarge or shrink the selection highlight.
static const double _padding = 10.0;
Rect _getSelectionHighlightRect() {
return Rect.fromLTWH(0 - _padding, 0 - _padding, size.width + _padding * 2, size.height + _padding * 2);
}
Offset? _start;
Offset? _end;
void _updateGeometry() {
if (_start == null || _end == null) {
_geometry.value = _noSelection;
return;
}
final Rect renderObjectRect = Rect.fromLTWH(0, 0, size.width, size.height);
final Rect selectionRect = Rect.fromPoints(_start!, _end!);
if (renderObjectRect.intersect(selectionRect).isEmpty) {
_geometry.value = _noSelection;
} else {
final Rect selectionRect = _getSelectionHighlightRect();
final SelectionPoint firstSelectionPoint = SelectionPoint(
localPosition: selectionRect.bottomLeft,
lineHeight: selectionRect.size.height,
handleType: TextSelectionHandleType.left,
);
final SelectionPoint secondSelectionPoint = SelectionPoint(
localPosition: selectionRect.bottomRight,
lineHeight: selectionRect.size.height,
handleType: TextSelectionHandleType.right,
);
final bool isReversed;
if (_start!.dy > _end!.dy) {
isReversed = true;
} else if (_start!.dy < _end!.dy) {
isReversed = false;
} else {
isReversed = _start!.dx > _end!.dx;
}
_geometry.value = SelectionGeometry(
status: SelectionStatus.uncollapsed,
hasContent: true,
startSelectionPoint: isReversed ? secondSelectionPoint : firstSelectionPoint,
endSelectionPoint: isReversed ? firstSelectionPoint : secondSelectionPoint,
selectionRects: <Rect>[selectionRect],
);
}
}
@override
SelectionResult dispatchSelectionEvent(SelectionEvent event) {
SelectionResult result = SelectionResult.none;
switch (event.type) {
case SelectionEventType.startEdgeUpdate:
case SelectionEventType.endEdgeUpdate:
final Rect renderObjectRect = Rect.fromLTWH(0, 0, size.width, size.height);
// Normalize offset in case it is out side of the rect.
final Offset point = globalToLocal((event as SelectionEdgeUpdateEvent).globalPosition);
final Offset adjustedPoint = SelectionUtils.adjustDragOffset(renderObjectRect, point);
if (event.type == SelectionEventType.startEdgeUpdate) {
_start = adjustedPoint;
} else {
_end = adjustedPoint;
}
result = SelectionUtils.getResultBasedOnRect(renderObjectRect, point);
case SelectionEventType.clear:
_start = _end = null;
case SelectionEventType.selectAll:
case SelectionEventType.selectWord:
_start = Offset.zero;
_end = Offset.infinite;
case SelectionEventType.granularlyExtendSelection:
result = SelectionResult.end;
final GranularlyExtendSelectionEvent extendSelectionEvent = event as GranularlyExtendSelectionEvent;
// Initialize the offset it there is no ongoing selection.
if (_start == null || _end == null) {
if (extendSelectionEvent.forward) {
_start = _end = Offset.zero;
} else {
_start = _end = Offset.infinite;
}
}
// Move the corresponding selection edge.
final Offset newOffset = extendSelectionEvent.forward ? Offset.infinite : Offset.zero;
if (extendSelectionEvent.isEnd) {
if (newOffset == _end) {
result = extendSelectionEvent.forward ? SelectionResult.next : SelectionResult.previous;
}
_end = newOffset;
} else {
if (newOffset == _start) {
result = extendSelectionEvent.forward ? SelectionResult.next : SelectionResult.previous;
}
_start = newOffset;
}
case SelectionEventType.directionallyExtendSelection:
result = SelectionResult.end;
final DirectionallyExtendSelectionEvent extendSelectionEvent = event as DirectionallyExtendSelectionEvent;
// Convert to local coordinates.
final double horizontalBaseLine = globalToLocal(Offset(event.dx, 0)).dx;
final Offset newOffset;
final bool forward;
switch (extendSelectionEvent.direction) {
case SelectionExtendDirection.backward:
case SelectionExtendDirection.previousLine:
forward = false;
// Initialize the offset it there is no ongoing selection.
if (_start == null || _end == null) {
_start = _end = Offset.infinite;
}
// Move the corresponding selection edge.
if (extendSelectionEvent.direction == SelectionExtendDirection.previousLine || horizontalBaseLine < 0) {
newOffset = Offset.zero;
} else {
newOffset = Offset.infinite;
}
case SelectionExtendDirection.nextLine:
case SelectionExtendDirection.forward:
forward = true;
// Initialize the offset it there is no ongoing selection.
if (_start == null || _end == null) {
_start = _end = Offset.zero;
}
// Move the corresponding selection edge.
if (extendSelectionEvent.direction == SelectionExtendDirection.nextLine ||
horizontalBaseLine > size.width) {
newOffset = Offset.infinite;
} else {
newOffset = Offset.zero;
}
}
if (extendSelectionEvent.isEnd) {
if (newOffset == _end) {
result = forward ? SelectionResult.next : SelectionResult.previous;
}
_end = newOffset;
} else {
if (newOffset == _start) {
result = forward ? SelectionResult.next : SelectionResult.previous;
}
_start = newOffset;
}
}
_updateGeometry();
return result;
}
// This method is called when users want to copy selected content in this
// widget into clipboard.
@override
SelectedContent? getSelectedContent() {
return value.hasSelection ? const SelectedContent(plainText: 'Custom Text') : null;
}
LayerLink? _startHandle;
LayerLink? _endHandle;
@override
void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) {
if (_startHandle == startHandle && _endHandle == endHandle) {
return;
}
_startHandle = startHandle;
_endHandle = endHandle;
markNeedsPaint();
}
@override
void paint(PaintingContext context, Offset offset) {
super.paint(context, offset);
if (!_geometry.value.hasSelection) {
return;
}
// Draw the selection highlight.
final Paint selectionPaint = Paint()
..style = PaintingStyle.fill
..color = _selectionColor;
context.canvas.drawRect(_getSelectionHighlightRect().shift(offset), selectionPaint);
// Push the layer links if any.
if (_startHandle != null) {
context.pushLayer(
LeaderLayer(
link: _startHandle!,
offset: offset + value.startSelectionPoint!.localPosition,
),
(PaintingContext context, Offset offset) {},
Offset.zero,
);
}
if (_endHandle != null) {
context.pushLayer(
LeaderLayer(
link: _endHandle!,
offset: offset + value.endSelectionPoint!.localPosition,
),
(PaintingContext context, Offset offset) {},
Offset.zero,
);
}
}
@override
void dispose() {
_geometry.dispose();
super.dispose();
}
}
| flutter/examples/api/lib/material/selectable_region/selectable_region.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/selectable_region/selectable_region.0.dart",
"repo_id": "flutter",
"token_count": 4224
} | 575 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [Switch].
void main() => runApp(const SwitchApp());
class SwitchApp extends StatelessWidget {
const SwitchApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(useMaterial3: true).copyWith(
// Use the ambient CupertinoThemeData to style all widgets which would
// otherwise use iOS defaults.
cupertinoOverrideTheme: const CupertinoThemeData(applyThemeToAll: true),
),
home: Scaffold(
appBar: AppBar(title: const Text('Switch Sample')),
body: const Center(
child: SwitchExample(),
),
),
);
}
}
class SwitchExample extends StatefulWidget {
const SwitchExample({super.key});
@override
State<SwitchExample> createState() => _SwitchExampleState();
}
class _SwitchExampleState extends State<SwitchExample> {
bool light = true;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch.adaptive(
value: light,
onChanged: (bool value) {
setState(() {
light = value;
});
},
),
Switch.adaptive(
// Don't use the ambient CupertinoThemeData to style this switch.
applyCupertinoTheme: false,
value: light,
onChanged: (bool value) {
setState(() {
light = value;
});
},
),
],
);
}
}
| flutter/examples/api/lib/material/switch/switch.3.dart/0 | {
"file_path": "flutter/examples/api/lib/material/switch/switch.3.dart",
"repo_id": "flutter",
"token_count": 726
} | 576 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
/// Flutter code sample for [ThemeExtension].
@immutable
class MyColors extends ThemeExtension<MyColors> {
const MyColors({
required this.brandColor,
required this.danger,
});
final Color? brandColor;
final Color? danger;
@override
MyColors copyWith({Color? brandColor, Color? danger}) {
return MyColors(
brandColor: brandColor ?? this.brandColor,
danger: danger ?? this.danger,
);
}
@override
MyColors lerp(MyColors? other, double t) {
if (other is! MyColors) {
return this;
}
return MyColors(
brandColor: Color.lerp(brandColor, other.brandColor, t),
danger: Color.lerp(danger, other.danger, t),
);
}
// Optional
@override
String toString() => 'MyColors(brandColor: $brandColor, danger: $danger)';
}
void main() {
// Slow down time to see lerping.
timeDilation = 5.0;
runApp(const ThemeExtensionExampleApp());
}
class ThemeExtensionExampleApp extends StatefulWidget {
const ThemeExtensionExampleApp({super.key});
@override
State<ThemeExtensionExampleApp> createState() => _ThemeExtensionExampleAppState();
}
class _ThemeExtensionExampleAppState extends State<ThemeExtensionExampleApp> {
bool isLightTheme = true;
void toggleTheme() {
setState(() => isLightTheme = !isLightTheme);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light().copyWith(
extensions: <ThemeExtension<dynamic>>[
const MyColors(
brandColor: Color(0xFF1E88E5),
danger: Color(0xFFE53935),
),
],
),
darkTheme: ThemeData.dark().copyWith(
extensions: <ThemeExtension<dynamic>>[
const MyColors(
brandColor: Color(0xFF90CAF9),
danger: Color(0xFFEF9A9A),
),
],
),
themeMode: isLightTheme ? ThemeMode.light : ThemeMode.dark,
home: Home(
isLightTheme: isLightTheme,
toggleTheme: toggleTheme,
),
);
}
}
class Home extends StatelessWidget {
const Home({
super.key,
required this.isLightTheme,
required this.toggleTheme,
});
final bool isLightTheme;
final void Function() toggleTheme;
@override
Widget build(BuildContext context) {
final MyColors myColors = Theme.of(context).extension<MyColors>()!;
return Material(
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(width: 100, height: 100, color: myColors.brandColor),
const SizedBox(width: 10),
Container(width: 100, height: 100, color: myColors.danger),
const SizedBox(width: 50),
IconButton(
icon: Icon(isLightTheme ? Icons.nightlight : Icons.wb_sunny),
onPressed: toggleTheme,
),
],
),
),
);
}
}
| flutter/examples/api/lib/material/theme/theme_extension.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/theme/theme_extension.1.dart",
"repo_id": "flutter",
"token_count": 1281
} | 577 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// Flutter code sample for [GrowthDirection]s.
void main() => runApp(const ExampleApp());
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyWidget(),
);
}
}
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final List<String> _alphabet = <String>[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
final Widget _spacer = const SizedBox.square(dimension: 10);
final UniqueKey _center = UniqueKey();
AxisDirection _axisDirection = AxisDirection.down;
Widget _getArrows(AxisDirection axisDirection) {
final Widget arrow;
switch (axisDirection) {
case AxisDirection.up:
arrow = const Icon(Icons.arrow_upward_rounded);
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[arrow, arrow],
);
case AxisDirection.down:
arrow = const Icon(Icons.arrow_downward_rounded);
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[arrow, arrow],
);
case AxisDirection.left:
arrow = const Icon(Icons.arrow_back_rounded);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[arrow, arrow],
);
case AxisDirection.right:
arrow = const Icon(Icons.arrow_forward_rounded);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[arrow, arrow],
);
}
}
void _onAxisDirectionChanged(AxisDirection? axisDirection) {
if (axisDirection != null && axisDirection != _axisDirection) {
setState(() {
// Respond to change in axis direction.
_axisDirection = axisDirection;
});
}
}
Widget _getLeading(SliverConstraints constraints, bool isForward) {
return Container(
color: isForward ? Colors.orange[300] : Colors.green[400],
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(constraints.axis.toString()),
_spacer,
Text(constraints.axisDirection.toString()),
_spacer,
Text(constraints.growthDirection.toString()),
_spacer,
_getArrows(
isForward
? _axisDirection
// This method is available to conveniently flip an AxisDirection
// into its opposite direction.
: flipAxisDirection(_axisDirection),
),
],
),
);
}
Widget _getRadioRow() {
return DefaultTextStyle(
style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
child: RadioTheme(
data: RadioThemeData(
fillColor: MaterialStateProperty.all<Color>(Colors.white),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Radio<AxisDirection>(
value: AxisDirection.up,
groupValue: _axisDirection,
onChanged: _onAxisDirectionChanged,
),
const Text('up'),
_spacer,
Radio<AxisDirection>(
value: AxisDirection.down,
groupValue: _axisDirection,
onChanged: _onAxisDirectionChanged,
),
const Text('down'),
_spacer,
Radio<AxisDirection>(
value: AxisDirection.left,
groupValue: _axisDirection,
onChanged: _onAxisDirectionChanged,
),
const Text('left'),
_spacer,
Radio<AxisDirection>(
value: AxisDirection.right,
groupValue: _axisDirection,
onChanged: _onAxisDirectionChanged,
),
const Text('right'),
_spacer,
],
),
),
),
);
}
Widget _getList({required bool isForward}) {
// The SliverLayoutBuilder is not necessary, and is here to allow us to see
// the SliverConstraints & directional information that is provided to the
// SliverList when laying out.
return SliverLayoutBuilder(
builder: (BuildContext context, SliverConstraints constraints) {
return SliverList.builder(
itemCount: 27,
itemBuilder: (BuildContext context, int index) {
final Widget child;
if (index == 0) {
child = _getLeading(constraints, isForward);
} else {
child = Container(
color: isForward
? (index.isEven ? Colors.amber[100] : Colors.amberAccent)
: (index.isEven ? Colors.green[100] : Colors.lightGreen),
padding: const EdgeInsets.all(8.0),
child: Center(child: Text(_alphabet[index - 1])),
);
}
return Padding(
padding: const EdgeInsets.all(8.0),
child: child,
);
},
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GrowthDirections'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(50),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: _getRadioRow(),
),
),
),
body: CustomScrollView(
// This method is available to conveniently determine if an scroll
// view is reversed by its AxisDirection.
reverse: axisDirectionIsReversed(_axisDirection),
// This method is available to conveniently convert an AxisDirection
// into its Axis.
scrollDirection: axisDirectionToAxis(_axisDirection),
// Places the leading edge of the center sliver in the middle of the
// viewport. Changing this value between 0.0 (the default) and 1.0
// changes the position of the inflection point between GrowthDirections
// in the viewport when the slivers are laid out.
anchor: 0.5,
center: _center,
slivers: <Widget>[
_getList(isForward: false),
SliverToBoxAdapter(
// This sliver will be located at the anchor. The scroll position
// will progress in either direction from this point.
key: _center,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Center(child: Text('0', style: TextStyle(fontWeight: FontWeight.bold))),
),
),
_getList(isForward: true),
],
),
);
}
}
| flutter/examples/api/lib/rendering/growth_direction/growth_direction.0.dart/0 | {
"file_path": "flutter/examples/api/lib/rendering/growth_direction/growth_direction.0.dart",
"repo_id": "flutter",
"token_count": 3373
} | 578 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [AnimatedSize].
void main() => runApp(const AnimatedSizeExampleApp());
class AnimatedSizeExampleApp extends StatelessWidget {
const AnimatedSizeExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('AnimatedSize Sample')),
body: const Center(
child: AnimatedSizeExample(),
),
),
);
}
}
class AnimatedSizeExample extends StatefulWidget {
const AnimatedSizeExample({super.key});
@override
State<AnimatedSizeExample> createState() => _AnimatedSizeExampleState();
}
class _AnimatedSizeExampleState extends State<AnimatedSizeExample> {
double _size = 50.0;
bool _large = false;
void _updateSize() {
setState(() {
_size = _large ? 250.0 : 100.0;
_large = !_large;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => _updateSize(),
child: ColoredBox(
color: Colors.amberAccent,
child: AnimatedSize(
curve: Curves.easeIn,
duration: const Duration(seconds: 1),
child: FlutterLogo(size: _size),
),
),
);
}
}
| flutter/examples/api/lib/widgets/animated_size/animated_size.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/animated_size/animated_size.0.dart",
"repo_id": "flutter",
"token_count": 534
} | 579 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ClipRRect].
void main() => runApp(const ClipRRectApp());
class ClipRRectApp extends StatelessWidget {
const ClipRRectApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ClipRRect Sample')),
body: const ClipRRectExample(),
),
);
}
}
class ClipRRectExample extends StatelessWidget {
const ClipRRectExample({super.key});
@override
Widget build(BuildContext context) {
const TextStyle style = TextStyle(color: Colors.white);
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
alignment: Alignment.center,
constraints: const BoxConstraints(
maxWidth: 300,
maxHeight: 100,
),
color: Colors.blue,
child: const Text('No ClipRRect', style: style),
),
ClipRRect(
borderRadius: BorderRadius.circular(30.0),
child: Container(
alignment: Alignment.center,
constraints: const BoxConstraints(
maxWidth: 300,
maxHeight: 100,
),
color: Colors.green,
child: const Text('ClipRRect', style: style),
),
),
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10.0),
topRight: Radius.circular(20.0),
bottomRight: Radius.circular(30.0),
bottomLeft: Radius.circular(40.0),
),
child: Container(
alignment: Alignment.center,
constraints: const BoxConstraints(
maxWidth: 300,
maxHeight: 100,
),
color: Colors.purple,
child: const Text('ClipRRect', style: style),
),
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/basic/clip_rrect.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/basic/clip_rrect.0.dart",
"repo_id": "flutter",
"token_count": 1070
} | 580 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [PhysicalShape].
void main() => runApp(const PhysicalShapeApp());
class PhysicalShapeApp extends StatelessWidget {
const PhysicalShapeApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('PhysicalShape Sample'),
),
body: const Center(child: PhysicalShapeExample()),
),
);
}
}
class PhysicalShapeExample extends StatelessWidget {
const PhysicalShapeExample({super.key});
@override
Widget build(BuildContext context) {
return PhysicalShape(
elevation: 5.0,
clipper: ShapeBorderClipper(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
color: Colors.orange,
child: const SizedBox(
height: 200.0,
width: 200.0,
child: Center(
child: Text(
'Hello, World!',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/basic/physical_shape.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/basic/physical_shape.0.dart",
"repo_id": "flutter",
"token_count": 552
} | 581 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [FocusTraversalGroup].
void main() => runApp(const FocusTraversalGroupExampleApp());
class FocusTraversalGroupExampleApp extends StatelessWidget {
const FocusTraversalGroupExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: FocusTraversalGroupExample(),
);
}
}
/// A button wrapper that adds either a numerical or lexical order, depending on
/// the type of T.
class OrderedButton<T> extends StatefulWidget {
const OrderedButton({
super.key,
required this.name,
this.canRequestFocus = true,
this.autofocus = false,
required this.order,
});
final String name;
final bool canRequestFocus;
final bool autofocus;
final T order;
@override
State<OrderedButton<T>> createState() => _OrderedButtonState<T>();
}
class _OrderedButtonState<T> extends State<OrderedButton<T>> {
late FocusNode focusNode;
@override
void initState() {
super.initState();
focusNode = FocusNode(
debugLabel: widget.name,
canRequestFocus: widget.canRequestFocus,
);
}
@override
void dispose() {
focusNode.dispose();
super.dispose();
}
@override
void didUpdateWidget(OrderedButton<T> oldWidget) {
super.didUpdateWidget(oldWidget);
focusNode.canRequestFocus = widget.canRequestFocus;
}
void _handleOnPressed() {
focusNode.requestFocus();
debugPrint('Button ${widget.name} pressed.');
debugDumpFocusTree();
}
@override
Widget build(BuildContext context) {
FocusOrder order;
if (widget.order is num) {
order = NumericFocusOrder((widget.order as num).toDouble());
} else {
order = LexicalFocusOrder(widget.order.toString());
}
Color? overlayColor(Set<MaterialState> states) {
if (states.contains(MaterialState.focused)) {
return Colors.red;
}
if (states.contains(MaterialState.hovered)) {
return Colors.blue;
}
return null; // defer to the default overlayColor
}
Color? foregroundColor(Set<MaterialState> states) {
if (states.contains(MaterialState.focused) || states.contains(MaterialState.hovered)) {
return Colors.white;
}
return null; // defer to the default foregroundColor
}
return FocusTraversalOrder(
order: order,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: OutlinedButton(
focusNode: focusNode,
autofocus: widget.autofocus,
style: ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color?>(overlayColor),
foregroundColor: MaterialStateProperty.resolveWith<Color?>(foregroundColor),
),
onPressed: () => _handleOnPressed(),
child: Text(widget.name),
),
),
);
}
}
class FocusTraversalGroupExample extends StatelessWidget {
const FocusTraversalGroupExample({super.key});
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Colors.white,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// A group that is ordered with a numerical order, from left to right.
FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(3, (int index) {
return OrderedButton<num>(
name: 'num: $index',
// TRY THIS: change this to "3 - index" and see how the order changes.
order: index,
);
}),
),
),
// A group that is ordered with a lexical order, from right to left.
FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(3, (int index) {
// Order as "C" "B", "A".
final String order = String.fromCharCode('A'.codeUnitAt(0) + (2 - index));
return OrderedButton<String>(
name: 'String: $order',
order: order,
);
}),
),
),
// A group that orders in widget order, regardless of what the order is set to.
FocusTraversalGroup(
// Because this is NOT an OrderedTraversalPolicy, the
// assigned order of these OrderedButtons is ignored, and they
// are traversed in widget order. TRY THIS: change this to
// "OrderedTraversalPolicy()" and see that it now follows the
// numeric order set on them instead of the widget order.
policy: WidgetOrderTraversalPolicy(),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(3, (int index) {
return OrderedButton<num>(
name: 'ignored num: ${3 - index}',
order: 3 - index,
);
}),
),
),
],
),
),
);
}
}
| flutter/examples/api/lib/widgets/focus_traversal/focus_traversal_group.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/focus_traversal/focus_traversal_group.0.dart",
"repo_id": "flutter",
"token_count": 2432
} | 582 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [AnimatedContainer].
void main() => runApp(const AnimatedContainerExampleApp());
class AnimatedContainerExampleApp extends StatelessWidget {
const AnimatedContainerExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('AnimatedContainer Sample')),
body: const AnimatedContainerExample(),
),
);
}
}
class AnimatedContainerExample extends StatefulWidget {
const AnimatedContainerExample({super.key});
@override
State<AnimatedContainerExample> createState() => _AnimatedContainerExampleState();
}
class _AnimatedContainerExampleState extends State<AnimatedContainerExample> {
bool selected = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
selected = !selected;
});
},
child: Center(
child: AnimatedContainer(
width: selected ? 200.0 : 100.0,
height: selected ? 100.0 : 200.0,
color: selected ? Colors.red : Colors.blue,
alignment: selected ? Alignment.center : AlignmentDirectional.topCenter,
duration: const Duration(seconds: 2),
curve: Curves.fastOutSlowIn,
child: const FlutterLogo(size: 75),
),
),
);
}
}
| flutter/examples/api/lib/widgets/implicit_animations/animated_container.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/implicit_animations/animated_container.0.dart",
"repo_id": "flutter",
"token_count": 559
} | 583 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [Navigator].
void main() => runApp(const NavigatorExampleApp());
class NavigatorExampleApp extends StatelessWidget {
const NavigatorExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
// MaterialApp contains our top-level Navigator
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => const HomePage(),
'/signup': (BuildContext context) => const SignUpPage(),
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.headlineMedium!,
child: Container(
color: Colors.white,
alignment: Alignment.center,
child: const Text('Home Page'),
),
);
}
}
class CollectPersonalInfoPage extends StatelessWidget {
const CollectPersonalInfoPage({super.key});
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.headlineMedium!,
child: GestureDetector(
onTap: () {
// This moves from the personal info page to the credentials page,
// replacing this page with that one.
Navigator.of(context).pushReplacementNamed('signup/choose_credentials');
},
child: Container(
color: Colors.lightBlue,
alignment: Alignment.center,
child: const Text('Collect Personal Info Page'),
),
),
);
}
}
class ChooseCredentialsPage extends StatelessWidget {
const ChooseCredentialsPage({
super.key,
required this.onSignupComplete,
});
final VoidCallback onSignupComplete;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onSignupComplete,
child: DefaultTextStyle(
style: Theme.of(context).textTheme.headlineMedium!,
child: Container(
color: Colors.pinkAccent,
alignment: Alignment.center,
child: const Text('Choose Credentials Page'),
),
),
);
}
}
class SignUpPage extends StatelessWidget {
const SignUpPage({super.key});
@override
Widget build(BuildContext context) {
// SignUpPage builds its own Navigator which ends up being a nested
// Navigator in our app.
return Navigator(
initialRoute: 'signup/personal_info',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder builder;
switch (settings.name) {
case 'signup/personal_info':
// Assume CollectPersonalInfoPage collects personal info and then
// navigates to 'signup/choose_credentials'.
builder = (BuildContext context) => const CollectPersonalInfoPage();
case 'signup/choose_credentials':
// Assume ChooseCredentialsPage collects new credentials and then
// invokes 'onSignupComplete()'.
builder = (BuildContext _) => ChooseCredentialsPage(
onSignupComplete: () {
// Referencing Navigator.of(context) from here refers to the
// top level Navigator because SignUpPage is above the
// nested Navigator that it created. Therefore, this pop()
// will pop the entire "sign up" journey and return to the
// "/" route, AKA HomePage.
Navigator.of(context).pop();
},
);
default:
throw Exception('Invalid route: ${settings.name}');
}
return MaterialPageRoute<void>(builder: builder, settings: settings);
},
);
}
}
| flutter/examples/api/lib/widgets/navigator/navigator.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/navigator/navigator.0.dart",
"repo_id": "flutter",
"token_count": 1536
} | 584 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [Overlay].
void main() => runApp(const OverlayApp());
class OverlayApp extends StatelessWidget {
const OverlayApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: OverlayExample(),
);
}
}
class OverlayExample extends StatefulWidget {
const OverlayExample({super.key});
@override
State<OverlayExample> createState() => _OverlayExampleState();
}
class _OverlayExampleState extends State<OverlayExample> {
OverlayEntry? overlayEntry;
int currentPageIndex = 0;
void createHighlightOverlay({
required AlignmentDirectional alignment,
required Color borderColor,
}) {
// Remove the existing OverlayEntry.
removeHighlightOverlay();
assert(overlayEntry == null);
overlayEntry = OverlayEntry(
// Create a new OverlayEntry.
builder: (BuildContext context) {
// Align is used to position the highlight overlay
// relative to the NavigationBar destination.
return SafeArea(
child: Align(
alignment: alignment,
heightFactor: 1.0,
child: DefaultTextStyle(
style: const TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 14.0,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Tap here for'),
Builder(builder: (BuildContext context) {
switch (currentPageIndex) {
case 0:
return const Column(
children: <Widget>[
Text(
'Explore page',
style: TextStyle(
color: Colors.red,
),
),
Icon(
Icons.arrow_downward,
color: Colors.red,
),
],
);
case 1:
return const Column(
children: <Widget>[
Text(
'Commute page',
style: TextStyle(
color: Colors.green,
),
),
Icon(
Icons.arrow_downward,
color: Colors.green,
),
],
);
case 2:
return const Column(
children: <Widget>[
Text(
'Saved page',
style: TextStyle(
color: Colors.orange,
),
),
Icon(
Icons.arrow_downward,
color: Colors.orange,
),
],
);
default:
return const Text('No page selected.');
}
}),
SizedBox(
width: MediaQuery.of(context).size.width / 3,
height: 80.0,
child: Center(
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: borderColor,
width: 4.0,
),
),
),
),
),
],
),
),
),
);
},
);
// Add the OverlayEntry to the Overlay.
Overlay.of(context, debugRequiredFor: widget).insert(overlayEntry!);
}
// Remove the OverlayEntry.
void removeHighlightOverlay() {
overlayEntry?.remove();
overlayEntry?.dispose();
overlayEntry = null;
}
@override
void dispose() {
// Make sure to remove OverlayEntry when the widget is disposed.
removeHighlightOverlay();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Overlay Sample'),
),
bottomNavigationBar: NavigationBar(
selectedIndex: currentPageIndex,
destinations: const <NavigationDestination>[
NavigationDestination(
icon: Icon(Icons.explore),
label: 'Explore',
),
NavigationDestination(
icon: Icon(Icons.commute),
label: 'Commute',
),
NavigationDestination(
selectedIcon: Icon(Icons.bookmark),
icon: Icon(Icons.bookmark_border),
label: 'Saved',
),
],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Use Overlay to highlight a NavigationBar destination',
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// This creates a highlight Overlay for
// the Explore item.
ElevatedButton(
onPressed: () {
setState(() {
currentPageIndex = 0;
});
createHighlightOverlay(
alignment: AlignmentDirectional.bottomStart,
borderColor: Colors.red,
);
},
child: const Text('Explore'),
),
const SizedBox(width: 20.0),
// This creates a highlight Overlay for
// the Commute item.
ElevatedButton(
onPressed: () {
setState(() {
currentPageIndex = 1;
});
createHighlightOverlay(
alignment: AlignmentDirectional.bottomCenter,
borderColor: Colors.green,
);
},
child: const Text('Commute'),
),
const SizedBox(width: 20.0),
// This creates a highlight Overlay for
// the Saved item.
ElevatedButton(
onPressed: () {
setState(() {
currentPageIndex = 2;
});
createHighlightOverlay(
alignment: AlignmentDirectional.bottomEnd,
borderColor: Colors.orange,
);
},
child: const Text('Saved'),
),
],
),
const SizedBox(height: 10.0),
ElevatedButton(
onPressed: () {
removeHighlightOverlay();
},
child: const Text('Remove Overlay'),
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/overlay/overlay.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/overlay/overlay.0.dart",
"repo_id": "flutter",
"token_count": 4472
} | 585 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [ScrollController].
void main() => runApp(const ScrollControllerDemo());
class ScrollControllerDemo extends StatefulWidget {
const ScrollControllerDemo({super.key});
@override
State<ScrollControllerDemo> createState() => _ScrollControllerDemoState();
}
class _ScrollControllerDemoState extends State<ScrollControllerDemo> {
late final ScrollController _controller;
bool isScrolling = false;
void _handleScrollChange() {
if (isScrolling != _controller.position.isScrollingNotifier.value) {
setState((){
isScrolling = _controller.position.isScrollingNotifier.value;
});
}
}
void _handlePositionAttach(ScrollPosition position) {
// From here, add a listener to the given ScrollPosition.
// Here the isScrollingNotifier will be used to inform when scrolling starts
// and stops and change the AppBar's color in response.
position.isScrollingNotifier.addListener(_handleScrollChange);
}
void _handlePositionDetach(ScrollPosition position) {
// From here, add a listener to the given ScrollPosition.
// Here the isScrollingNotifier will be used to inform when scrolling starts
// and stops and change the AppBar's color in response.
position.isScrollingNotifier.removeListener(_handleScrollChange);
}
@override
void initState() {
_controller = ScrollController(
// These methods will be called in response to a scroll position
// being attached to or detached from this ScrollController. This happens
// when the Scrollable is built.
onAttach: _handlePositionAttach,
onDetach: _handlePositionDetach,
);
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(isScrolling ? 'Scrolling' : 'Not Scrolling'),
backgroundColor: isScrolling
? Colors.green[800]!.withOpacity(.85)
: Colors.redAccent[700]!.withOpacity(.85),
),
// ListView.builder works very similarly to this example with
// CustomScrollView & SliverList.
body: CustomScrollView(
// Provide the scroll controller to the scroll view.
controller: _controller,
slivers: <Widget>[
SliverList.builder(
itemCount: 50,
itemBuilder: (_, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: DecoratedBox(
decoration: BoxDecoration(
color: Colors.blueGrey[50],
boxShadow: const <BoxShadow>[
BoxShadow(
color: Colors.black12,
offset: Offset(5, 5),
blurRadius: 5,
),
],
borderRadius: const BorderRadius.all(Radius.circular(10))
),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 12.0,
horizontal: 20.0,
),
child: Text('Item $index'),
),
),
),
);
},
),
],
),
),
);
}
}
| flutter/examples/api/lib/widgets/scroll_position/scroll_controller_on_attach.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/scroll_position/scroll_controller_on_attach.0.dart",
"repo_id": "flutter",
"token_count": 1650
} | 586 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [Shortcuts].
void main() => runApp(const ShortcutsExampleApp());
class ShortcutsExampleApp extends StatelessWidget {
const ShortcutsExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Shortcuts Sample')),
body: const Center(
child: ShortcutsExample(),
),
),
);
}
}
class IncrementIntent extends Intent {
const IncrementIntent();
}
class DecrementIntent extends Intent {
const DecrementIntent();
}
class ShortcutsExample extends StatefulWidget {
const ShortcutsExample({super.key});
@override
State<ShortcutsExample> createState() => _ShortcutsExampleState();
}
class _ShortcutsExampleState extends State<ShortcutsExample> {
int count = 0;
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowUp): IncrementIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): DecrementIntent(),
},
child: Actions(
actions: <Type, Action<Intent>>{
IncrementIntent: CallbackAction<IncrementIntent>(
onInvoke: (IncrementIntent intent) => setState(() {
count = count + 1;
}),
),
DecrementIntent: CallbackAction<DecrementIntent>(
onInvoke: (DecrementIntent intent) => setState(() {
count = count - 1;
}),
),
},
child: Focus(
autofocus: true,
child: Column(
children: <Widget>[
const Text('Add to the counter by pressing the up arrow key'),
const Text('Subtract from the counter by pressing the down arrow key'),
Text('count: $count'),
],
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/shortcuts/shortcuts.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/shortcuts/shortcuts.0.dart",
"repo_id": "flutter",
"token_count": 867
} | 587 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [TextFieldTapRegion].
void main() => runApp(const TapRegionApp());
class TapRegionApp extends StatelessWidget {
const TapRegionApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('TextFieldTapRegion Example')),
body: const TextFieldTapRegionExample(),
),
);
}
}
class TextFieldTapRegionExample extends StatefulWidget {
const TextFieldTapRegionExample({super.key});
@override
State<TextFieldTapRegionExample> createState() => _TextFieldTapRegionExampleState();
}
class _TextFieldTapRegionExampleState extends State<TextFieldTapRegionExample> {
int value = 0;
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: SizedBox(
width: 150,
height: 80,
child: IntegerSpinnerField(
value: value,
autofocus: true,
onChanged: (int newValue) {
if (value == newValue) {
// Avoid unnecessary redraws.
return;
}
setState(() {
// Update the value and redraw.
value = newValue;
});
},
),
),
),
),
],
);
}
}
/// An integer example of the generic [SpinnerField] that validates input and
/// increments by a delta.
class IntegerSpinnerField extends StatelessWidget {
const IntegerSpinnerField({
super.key,
required this.value,
this.autofocus = false,
this.delta = 1,
this.onChanged,
});
final int value;
final bool autofocus;
final int delta;
final ValueChanged<int>? onChanged;
@override
Widget build(BuildContext context) {
return SpinnerField<int>(
value: value,
onChanged: onChanged,
autofocus: autofocus,
fromString: (String stringValue) => int.tryParse(stringValue) ?? value,
increment: (int i) => i + delta,
decrement: (int i) => i - delta,
// Add a text formatter that only allows integer values and a leading
// minus sign.
inputFormatters: <TextInputFormatter>[
TextInputFormatter.withFunction(
(TextEditingValue oldValue, TextEditingValue newValue) {
String newString;
if (newValue.text.startsWith('-')) {
newString = '-${newValue.text.replaceAll(RegExp(r'\D'), '')}';
} else {
newString = newValue.text.replaceAll(RegExp(r'\D'), '');
}
return newValue.copyWith(
text: newString,
selection: newValue.selection.copyWith(
baseOffset: newValue.selection.baseOffset.clamp(0, newString.length),
extentOffset: newValue.selection.extentOffset.clamp(0, newString.length),
),
);
},
)
],
);
}
}
/// A generic "spinner" field example which adds extra buttons next to a
/// [TextField] to increment and decrement the value.
///
/// This widget uses [TextFieldTapRegion] to indicate that tapping on the
/// spinner buttons should not cause the text field to lose focus.
class SpinnerField<T> extends StatefulWidget {
SpinnerField({
super.key,
required this.value,
required this.fromString,
this.autofocus = false,
String Function(T value)? asString,
this.increment,
this.decrement,
this.onChanged,
this.inputFormatters = const <TextInputFormatter>[],
}) : asString = asString ?? ((T value) => value.toString());
final T value;
final T Function(T value)? increment;
final T Function(T value)? decrement;
final String Function(T value) asString;
final T Function(String value) fromString;
final ValueChanged<T>? onChanged;
final List<TextInputFormatter> inputFormatters;
final bool autofocus;
@override
State<SpinnerField<T>> createState() => _SpinnerFieldState<T>();
}
class _SpinnerFieldState<T> extends State<SpinnerField<T>> {
TextEditingController controller = TextEditingController();
@override
void initState() {
super.initState();
_updateText(widget.asString(widget.value));
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant SpinnerField<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.asString != widget.asString || oldWidget.value != widget.value) {
final String newText = widget.asString(widget.value);
_updateText(newText);
}
}
void _updateText(String text, {bool collapsed = true}) {
if (text != controller.text) {
controller.value = TextEditingValue(
text: text,
selection: collapsed
? TextSelection.collapsed(offset: text.length)
: TextSelection(baseOffset: 0, extentOffset: text.length),
);
}
}
void _spin(T Function(T value)? spinFunction) {
if (spinFunction == null) {
return;
}
final T newValue = spinFunction(widget.value);
widget.onChanged?.call(newValue);
_updateText(widget.asString(newValue), collapsed: false);
}
void _increment() {
_spin(widget.increment);
}
void _decrement() {
_spin(widget.decrement);
}
@override
Widget build(BuildContext context) {
return CallbackShortcuts(
bindings: <ShortcutActivator, VoidCallback>{
const SingleActivator(LogicalKeyboardKey.arrowUp): _increment,
const SingleActivator(LogicalKeyboardKey.arrowDown): _decrement,
},
child: Row(
children: <Widget>[
Expanded(
child: TextField(
autofocus: widget.autofocus,
inputFormatters: widget.inputFormatters,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
onChanged: (String value) => widget.onChanged?.call(widget.fromString(value)),
controller: controller,
textAlign: TextAlign.center,
),
),
const SizedBox(width: 12),
// Without this TextFieldTapRegion, tapping on the buttons below would
// increment the value, but it would cause the text field to be
// unfocused, since tapping outside of a text field should unfocus it
// on non-mobile platforms.
TextFieldTapRegion(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: OutlinedButton(
onPressed: _increment,
child: const Icon(Icons.add),
),
),
Expanded(
child: OutlinedButton(
onPressed: _decrement,
child: const Icon(Icons.remove),
),
),
],
),
)
],
),
);
}
}
| flutter/examples/api/lib/widgets/tap_region/text_field_tap_region.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/tap_region/text_field_tap_region.0.dart",
"repo_id": "flutter",
"token_count": 3190
} | 588 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Flutter code sample for [RotationTransition].
void main() => runApp(const RotationTransitionExampleApp());
class RotationTransitionExampleApp extends StatelessWidget {
const RotationTransitionExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: RotationTransitionExample(),
);
}
}
class RotationTransitionExample extends StatefulWidget {
const RotationTransitionExample({super.key});
@override
State<RotationTransitionExample> createState() => _RotationTransitionExampleState();
}
/// [AnimationController]s can be created with `vsync: this` because of
/// [TickerProviderStateMixin].
class _RotationTransitionExampleState extends State<RotationTransitionExample> with TickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
late final Animation<double> _animation = CurvedAnimation(
parent: _controller,
curve: Curves.elasticOut,
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RotationTransition(
turns: _animation,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: FlutterLogo(size: 150.0),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/transitions/rotation_transition.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/transitions/rotation_transition.0.dart",
"repo_id": "flutter",
"token_count": 560
} | 589 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_api_samples/cupertino/date_picker/cupertino_timer_picker.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
const Offset _kRowOffset = Offset(0.0, -50.0);
void main() {
testWidgets('Can pick a duration from CupertinoTimerPicker', (WidgetTester tester) async {
await tester.pumpWidget(
const example.TimerPickerApp(),
);
// Launch the timer picker.
await tester.tap(find.text('1:23:00.000000'));
await tester.pumpAndSettle();
// Drag hour, minute to change the time.
await tester.drag(find.text('1'), _kRowOffset, touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.drag(find.text('23'), _kRowOffset, touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
// Close the timer picker.
await tester.tapAt(const Offset(1.0, 1.0));
await tester.pumpAndSettle();
expect(find.text('3:25:00.000000'), findsOneWidget);
});
}
| flutter/examples/api/test/cupertino/date_picker/cupertino_timer_picker.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/date_picker/cupertino_timer_picker.0_test.dart",
"repo_id": "flutter",
"token_count": 436
} | 590 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/action_chip/action_chip.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('ActionChip updates avatar when tapped', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ChipApp(),
);
expect(find.byIcon(Icons.favorite_border), findsOneWidget);
await tester.tap(find.byType(ActionChip));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.favorite), findsOneWidget);
});
}
| flutter/examples/api/test/material/action_chip/action_chip.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/action_chip/action_chip.0_test.dart",
"repo_id": "flutter",
"token_count": 241
} | 591 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/choice_chip/choice_chip.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can choose an item using ChoiceChip', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ChipApp(),
);
ChoiceChip chosenChip = tester.widget(find.byType(ChoiceChip).at(1));
expect(chosenChip.selected, true);
await tester.tap(find.byType(ChoiceChip).at(0));
await tester.pumpAndSettle();
chosenChip = tester.widget(find.byType(ChoiceChip).at(0));
expect(chosenChip.selected, true);
});
}
| flutter/examples/api/test/material/choice_chip/choice_chip.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/choice_chip/choice_chip.0_test.dart",
"repo_id": "flutter",
"token_count": 282
} | 592 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/dialog/show_dialog.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Show dialog', (WidgetTester tester) async {
const String dialogTitle = 'Basic dialog title';
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.ShowDialogExampleApp(),
),
),
);
expect(find.text(dialogTitle), findsNothing);
await tester.tap(find.widgetWithText(OutlinedButton, 'Open Dialog'));
await tester.pumpAndSettle();
expect(find.text(dialogTitle), findsOneWidget);
await tester.tap(find.text('Enable'));
await tester.pumpAndSettle();
expect(find.text(dialogTitle), findsNothing);
});
}
| flutter/examples/api/test/material/dialog/show_dialog.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/dialog/show_dialog.0_test.dart",
"repo_id": "flutter",
"token_count": 347
} | 593 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_api_samples/material/expansion_tile/expansion_tile.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Test the basics of ExpansionTileControllerApp', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ExpansionTileControllerApp(),
);
expect(find.text('ExpansionTile Contents'), findsNothing);
expect(find.text('Collapse This Tile'), findsNothing);
await tester.tap(find.text('Expand/Collapse the Tile Above'));
await tester.pumpAndSettle();
expect(find.text('ExpansionTile Contents'), findsOneWidget);
await tester.tap(find.text('Expand/Collapse the Tile Above'));
await tester.pumpAndSettle();
expect(find.text('ExpansionTile Contents'), findsNothing);
await tester.tap(find.text('ExpansionTile with implicit controller.'));
await tester.pumpAndSettle();
expect(find.text('Collapse This Tile'), findsOneWidget);
await tester.tap(find.text('Collapse This Tile'));
await tester.pumpAndSettle();
expect(find.text('Collapse This Tile'), findsNothing);
});
}
| flutter/examples/api/test/material/expansion_tile/expansion_tile.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/expansion_tile/expansion_tile.1_test.dart",
"repo_id": "flutter",
"token_count": 417
} | 594 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/material/menu_anchor/menu_bar.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can open menu', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MenuBarApp(),
);
final Finder menuBarFinder = find.byType(MenuBar);
final MenuBar menuBar = tester.widget<MenuBar>(menuBarFinder);
expect(menuBar.children, isNotEmpty);
expect(menuBar.children.length, equals(1));
final Finder menuButtonFinder = find.byType(SubmenuButton).first;
await tester.tap(menuButtonFinder);
await tester.pumpAndSettle();
expect(find.text('About'), findsOneWidget);
expect(find.text('Show Message'), findsOneWidget);
expect(find.text('Reset Message'), findsOneWidget);
expect(find.text('Background Color'), findsOneWidget);
expect(find.text('Red Background'), findsNothing);
expect(find.text('Green Background'), findsNothing);
expect(find.text('Blue Background'), findsNothing);
expect(find.text(example.MenuBarApp.kMessage), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pumpAndSettle();
expect(find.text('About'), findsOneWidget);
expect(find.text('Show Message'), findsOneWidget);
expect(find.text('Reset Message'), findsOneWidget);
expect(find.text('Background Color'), findsOneWidget);
expect(find.text('Red Background'), findsOneWidget);
expect(find.text('Green Background'), findsOneWidget);
expect(find.text('Blue Background'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(find.text(example.MenuBarApp.kMessage), findsOneWidget);
expect(find.text('Last Selected: Show Message'), findsOneWidget);
});
testWidgets('Shortcuts work', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MenuBarApp(),
);
expect(find.text(example.MenuBarApp.kMessage), findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyS);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text(example.MenuBarApp.kMessage), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.text(example.MenuBarApp.kMessage), findsNothing);
expect(find.text('Last Selected: Reset Message'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyR);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: Red Background'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: Green Background'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyB);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: Blue Background'), findsOneWidget);
});
testWidgets('MenuBar is wrapped in a SafeArea', (WidgetTester tester) async {
const double safeAreaPadding = 100.0;
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(
padding: EdgeInsets.symmetric(vertical: safeAreaPadding),
),
child: example.MenuBarApp(),
),
);
expect(tester.getTopLeft(find.byType(MenuBar)), const Offset(0.0, safeAreaPadding));
});
}
| flutter/examples/api/test/material/menu_anchor/menu_bar.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/menu_anchor/menu_bar.0_test.dart",
"repo_id": "flutter",
"token_count": 1449
} | 595 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_api_samples/material/progress_indicator/circular_progress_indicator.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Finds CircularProgressIndicator', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ProgressIndicatorApp(),
);
expect(
find.bySemanticsLabel('Circular progress indicator'),
findsOneWidget,
);
// Test if CircularProgressIndicator is animating.
await tester.pump(const Duration(seconds: 2));
expect(tester.hasRunningAnimations, isTrue);
});
}
| flutter/examples/api/test/material/progress_indicator/circular_progress_indicator.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/progress_indicator/circular_progress_indicator.0_test.dart",
"repo_id": "flutter",
"token_count": 256
} | 596 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/switch/switch.2.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Switch thumb icon supports material states', (WidgetTester tester) async {
const Set<MaterialState> selected = <MaterialState>{ MaterialState.selected };
const Set<MaterialState> unselected = <MaterialState>{};
await tester.pumpWidget(
const example.SwitchApp(),
);
Switch materialSwitch = tester.widget<Switch>(find.byType(Switch).first);
expect(materialSwitch.thumbIcon, null);
materialSwitch = tester.widget<Switch>(find.byType(Switch).last);
expect(materialSwitch.thumbIcon, isNotNull);
expect(
materialSwitch.thumbIcon!.resolve(selected)!.icon,
Icons.check,
);
expect(
materialSwitch.thumbIcon!.resolve(unselected)!.icon,
Icons.close,
);
});
}
| flutter/examples/api/test/material/switch/switch.2_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/switch/switch.2_test.dart",
"repo_id": "flutter",
"token_count": 370
} | 597 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/toggle_buttons/toggle_buttons.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('ToggleButtons allows multiple or no selection', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
Finder findButton(String text) {
return find.descendant(
of: find.byType(ToggleButtons),
matching: find.widgetWithText(TextButton, text),
);
}
await tester.pumpWidget(const example.ToggleButtonsApp());
TextButton toggleMButton = tester.widget<TextButton>(findButton('M'));
TextButton toggleXLButton = tester.widget<TextButton>(findButton('XL'));
// Initially, only M is selected.
expect(
toggleMButton.style!.backgroundColor!.resolve(enabled),
theme.colorScheme.primary.withOpacity(0.12),
);
expect(
toggleXLButton.style!.backgroundColor!.resolve(enabled),
theme.colorScheme.surface.withOpacity(0.0),
);
// Tap on XL.
await tester.tap(findButton('XL'));
await tester.pumpAndSettle();
// Now both M and XL are selected.
toggleMButton = tester.widget<TextButton>(findButton('M'));
toggleXLButton = tester.widget<TextButton>(findButton('XL'));
expect(
toggleMButton.style!.backgroundColor!.resolve(enabled),
theme.colorScheme.primary.withOpacity(0.12),
);
expect(
toggleXLButton.style!.backgroundColor!.resolve(enabled),
theme.colorScheme.primary.withOpacity(0.12),
);
// Tap M to deselect it.
await tester.tap(findButton('M'));
await tester.pumpAndSettle();
// Tap XL to deselect it.
await tester.tap(findButton('XL'));
await tester.pumpAndSettle();
// Now neither M nor XL are selected.
toggleMButton = tester.widget<TextButton>(findButton('M'));
toggleXLButton = tester.widget<TextButton>(findButton('XL'));
expect(
toggleMButton.style!.backgroundColor!.resolve(enabled),
theme.colorScheme.surface.withOpacity(0.0),
);
expect(
toggleXLButton.style!.backgroundColor!.resolve(enabled),
theme.colorScheme.surface.withOpacity(0.0),
);
});
testWidgets('SegmentedButton allows multiple or no selection', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
Finder findButton(String text) {
return find.descendant(
of: find.byType(SegmentedButton<example.ShirtSize>),
matching: find.widgetWithText(TextButton, text),
);
}
await tester.pumpWidget(const example.ToggleButtonsApp());
Material segmentMButton = tester.widget<Material>(find.descendant(
of: findButton('M'),
matching: find.byType(Material),
));
Material segmentXLButton = tester.widget<Material>(find.descendant(
of: findButton('XL'),
matching: find.byType(Material),
));
// Initially, only M is selected.
expect(segmentMButton.color, theme.colorScheme.secondaryContainer);
expect(segmentXLButton.color, Colors.transparent);
// Tap on XL.
await tester.tap(findButton('XL'));
await tester.pumpAndSettle();
// // Now both M and XL are selected.
segmentMButton = tester.widget<Material>(find.descendant(
of: findButton('M'),
matching: find.byType(Material),
));
segmentXLButton = tester.widget<Material>(find.descendant(
of: findButton('XL'),
matching: find.byType(Material),
));
expect(segmentMButton.color, theme.colorScheme.secondaryContainer);
expect(segmentXLButton.color, theme.colorScheme.secondaryContainer);
// Tap M to deselect it.
await tester.tap(findButton('M'));
await tester.pumpAndSettle();
// Tap XL to deselect it.
await tester.tap(findButton('XL'));
await tester.pumpAndSettle();
// Now neither M nor XL are selected.
segmentMButton = tester.widget<Material>(find.descendant(
of: findButton('M'),
matching: find.byType(Material),
));
segmentXLButton = tester.widget<Material>(find.descendant(
of: findButton('XL'),
matching: find.byType(Material),
));
expect(segmentMButton.color, Colors.transparent);
expect(segmentXLButton.color, Colors.transparent);
});
}
Set<MaterialState> enabled = <MaterialState>{ };
| flutter/examples/api/test/material/toggle_buttons/toggle_buttons.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/toggle_buttons/toggle_buttons.1_test.dart",
"repo_id": "flutter",
"token_count": 1641
} | 598 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_api_samples/services/binding/handle_request_app_exit.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Application Exit example', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ApplicationExitExample(),
);
expect(find.text('No exit requested yet'), findsOneWidget);
expect(find.text('Do Not Allow Exit'), findsOneWidget);
expect(find.text('Allow Exit'), findsOneWidget);
expect(find.text('Quit'), findsOneWidget);
await tester.tap(find.text('Quit'));
await tester.pump();
expect(find.text('App requesting cancelable exit'), findsOneWidget);
});
}
| flutter/examples/api/test/services/binding/handle_request_app_exit.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/services/binding/handle_request_app_exit.0_test.dart",
"repo_id": "flutter",
"token_count": 275
} | 599 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/widgets/basic/expanded.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Expanded widgets in a Row', (WidgetTester tester) async {
const double rowWidth = 800.0;
const double rowHeight = 100.0;
const double containerOneWidth = (rowWidth - 50) * 2 / 3;
const double containerTwoWidth = 50;
const double containerThreeWidth = (rowWidth - 50) * 1 / 3;
await tester.pumpWidget(
const example.ExpandedApp(),
);
final Size row = tester.getSize(find.byType(Row));
expect(row, const Size(rowWidth, rowHeight));
// This container is wrapped in an Expanded widget, so it should take up
// two thirds of the remaining space in the Row.
final Size containerOne = tester.getSize(find.byType(Container).at(0));
expect(containerOne, const Size(containerOneWidth, rowHeight));
final Size containerTwo = tester.getSize(find.byType(Container).at(1));
expect(containerTwo, const Size(containerTwoWidth, rowHeight));
// This container is wrapped in an Expanded widget, so it should take up
// one third of the remaining space in the Row.
final Size containerThree = tester.getSize(find.byType(Container).at(2));
expect(containerThree, const Size(containerThreeWidth, rowHeight));
});
}
| flutter/examples/api/test/widgets/basic/expanded.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/basic/expanded.1_test.dart",
"repo_id": "flutter",
"token_count": 489
} | 600 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/widgets/editable_text/text_editing_controller.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Initial selection is collapsed at offset 0', (WidgetTester tester) async {
await tester.pumpWidget(
const example.TextEditingControllerExampleApp(),
);
final EditableText editableText = tester.widget(find.byType(EditableText));
final TextEditingController controller = editableText.controller;
expect(controller.text, 'Flutter');
expect(controller.selection, const TextSelection.collapsed(offset: 0));
});
}
| flutter/examples/api/test/widgets/editable_text/text_editing_controller.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/editable_text/text_editing_controller.1_test.dart",
"repo_id": "flutter",
"token_count": 256
} | 601 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_api_samples/widgets/overlay/overlay_portal.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
const String tooltipText = 'tooltip';
testWidgets('Tooltip is shown on press', (WidgetTester tester) async {
await tester.pumpWidget(const example.OverlayPortalExampleApp());
expect(find.text(tooltipText), findsNothing);
await tester.tap(find.byType(example.ClickableTooltipWidget));
await tester.pump();
expect(find.text(tooltipText), findsOneWidget);
await tester.tap(find.byType(example.ClickableTooltipWidget));
await tester.pump();
expect(find.text(tooltipText), findsNothing);
});
testWidgets('Tooltip is shown at the right location', (WidgetTester tester) async {
await tester.pumpWidget(const example.OverlayPortalExampleApp());
await tester.tap(find.byType(example.ClickableTooltipWidget));
await tester.pump();
final Size canvasSize = tester.getSize(find.byType(example.OverlayPortalExampleApp));
expect(
tester.getBottomRight(find.text(tooltipText)),
canvasSize - const Size(50, 50),
);
});
testWidgets('Tooltip is shown with the right font size', (WidgetTester tester) async {
await tester.pumpWidget(const example.OverlayPortalExampleApp());
await tester.tap(find.byType(example.ClickableTooltipWidget));
await tester.pump();
final TextSpan textSpan = tester.renderObject<RenderParagraph>(find.text(tooltipText)).text as TextSpan;
expect(textSpan.style?.fontSize, 50);
});
}
| flutter/examples/api/test/widgets/overlay/overlay_portal.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/overlay/overlay_portal.0_test.dart",
"repo_id": "flutter",
"token_count": 594
} | 602 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_api_samples/widgets/sliver/sliver_cross_axis_group.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SliverCrossAxisGroup example', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SliverCrossAxisGroupExampleApp(),
);
final RenderSliverCrossAxisGroup renderSliverGroup = tester.renderObject(find.byType(SliverCrossAxisGroup));
expect(renderSliverGroup, isNotNull);
final double crossAxisExtent = renderSliverGroup.constraints.crossAxisExtent;
final List<RenderSliverList> renderSliverLists = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList();
final RenderSliverList firstList = renderSliverLists[0];
final RenderSliverList secondList = renderSliverLists[1];
final RenderSliverList thirdList = renderSliverLists[2];
final double expectedFirstExtent = (crossAxisExtent - 200) / 3;
const double expectedSecondExtent = 200;
final double expectedThirdExtent = 2 * (crossAxisExtent - 200) / 3;
expect(firstList.constraints.crossAxisExtent, equals(expectedFirstExtent));
expect(secondList.constraints.crossAxisExtent, equals(expectedSecondExtent));
expect(thirdList.constraints.crossAxisExtent, equals(expectedThirdExtent));
// Also check that the paint offsets are correct.
final RenderSliverConstrainedCrossAxis renderConstrained = tester.renderObject<RenderSliverConstrainedCrossAxis>(
find.byType(SliverConstrainedCrossAxis)
);
expect((firstList.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0));
expect((renderConstrained.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(expectedFirstExtent));
expect((thirdList.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(expectedFirstExtent + expectedSecondExtent));
});
}
| flutter/examples/api/test/widgets/sliver/sliver_cross_axis_group.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/sliver/sliver_cross_axis_group.0_test.dart",
"repo_id": "flutter",
"token_count": 687
} | 603 |
{
"name": "flutter_api_samples",
"short_name": "flutter_api_samples",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A temporary code sample for Curve2D",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
| flutter/examples/api/web/manifest.json/0 | {
"file_path": "flutter/examples/api/web/manifest.json",
"repo_id": "flutter",
"token_count": 526
} | 604 |
#include "Generated.xcconfig"
| flutter/examples/image_list/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/examples/image_list/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 605 |
// Copyright 2014 The Flutter 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:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// An example that sets up local http server for serving single
/// image, creates single flutter widget with five copies of requested
/// image and prints how long the loading took.
///
/// This is used in [$FH/flutter/devicelab/bin/tasks/image_list_reported_duration.dart] test.
///
///
/// To generate new certificate:
///
/// $ openssl req -new -out image_list.csr
/// Generating a 2048 bit RSA private key
/// Enter PEM pass phrase: <random string>
/// ...
/// Common Name (eg, fully qualified host name) []:localhost
///
/// Copy content of the privateKey below into image_list.key file, then
/// $ openssl x509 -req -sha256 -days 3650 -in image_list.csr -signkey image_list.key -out image_list.crt
///
/// Copy content of the image_list.crt into certificate string below.
String certificate = '''
-----BEGIN CERTIFICATE-----
MIICpDCCAYwCCQD1kfAz8IhbazANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls
b2NhbGhvc3QwHhcNMjAwODI0MjE1MTUwWhcNMzAwODIyMjE1MTUwWjAUMRIwEAYD
VQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCi
/fmozdYuCIZbJS7y4zYPp2NRboLXrpUcUzzvzz+24k/TYUPNeRvf6wiNXHvr1ijM
g1j3wQP72RphxI7cY7XCwzRiM5QeQy3EtRz4ETYBzOev3mHLLEgZ9RnSq/u42siS
S9CNjoz97liPyQUq8h37/09qhYG0hR/2pRN+YB9g7sNYoGe2B7zkh3azRS0/Ltgl
tXwHUId7QzJc15W9Q7adsNVTpOCo7dOj2KWz6sEtFGkYfwLV5uiTslRdWCCOUD9i
ZjCtlPqALkGnWyhNiFJESLbVNC6MURyMngcALW0JTMwc2oDjMxtdNkMl0cdzPlhX
MDKIKpY9bWbRKUUdsfOnAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAHZo/Io7hE9P
jDhSSP+4iSwx6xjnkRjBHReoea+XwSCv1s9Alwe1Nub6u5jUBhCpGCyU4diKFV1W
zhunXKY+zRGGtr09nYoN9UVizS5fAFb+h2x3Tw8lsxs4JpPQeWTbGK9Ci+jyfuZu
xPvdU8I8oxiTRPoWa1KpPm6UVvcrjyftvbqJ4l7cZ8KZN4JNSZlphX8lIM14xR4H
12sFFTcYWPNDTqO1A9MSflG4OkG59LDHV36JAEqB61pP8hipowVp48+rzD2DVpqb
r/Mw+0x0HENUTMVExSA5rj/3fxNMggUSl2YsujVJjkb1LiQNPORX7rBndcjknAMt
TvaTkrwwZA4=
-----END CERTIFICATE-----
''';
String privateKey = '''
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCi/fmozdYuCIZb
JS7y4zYPp2NRboLXrpUcUzzvzz+24k/TYUPNeRvf6wiNXHvr1ijMg1j3wQP72Rph
xI7cY7XCwzRiM5QeQy3EtRz4ETYBzOev3mHLLEgZ9RnSq/u42siSS9CNjoz97liP
yQUq8h37/09qhYG0hR/2pRN+YB9g7sNYoGe2B7zkh3azRS0/LtgltXwHUId7QzJc
15W9Q7adsNVTpOCo7dOj2KWz6sEtFGkYfwLV5uiTslRdWCCOUD9iZjCtlPqALkGn
WyhNiFJESLbVNC6MURyMngcALW0JTMwc2oDjMxtdNkMl0cdzPlhXMDKIKpY9bWbR
KUUdsfOnAgMBAAECggEADUStiS9Qayjofwz02HLkmLugmyVq41Hj841XHZJ6dlHP
+74kPdrJCR5h8NgBgn5JjfR3TpvYziyrOCA/HPPE/RjU79WRDjGbzTKNLCiCg/0B
M1DgFyEAsZRBSOQVNsQgpcAkNxHOqnE3pmTP1eIlzLjI5zv9Bgv8QSDJCHWcuFA2
NrvGudq3dlFnZwjipx0k0E1hCsaClqLsi5jEXIBA6TX7RTeeXjC+j2/DlmTpBxo0
c34o/sSoCl+mfJDQ3QApXLFuycBl7nauO0M+VsUWrKYqHHr4NIcgoIpIX28QjWc/
Y2+iooMSBO1ToK2nPD8hZQwNDF8xz6Xf7QNkTOpnqQKBgQDNgfNYkEvgWxhSMmW7
cK06supZC/isj2JfQmlJc80JcAvf8rpynZLi4XWZWRo0PykM4szI91h3YHTG27VX
YVHSsFs+6FwP7fLAHR7FYn65p/bwTuqpWGjcmQhc0HWx7y45HRIoSK/m+Z7lNA/J
QxnCp1khTmhPqCNglo+38vZSzQKBgQDLCeBhji0K/BOmCrhNxRxrCvHYEd6gqRtC
+rKhco6mMrxma/UmggRKoGXg0yMcya3199y3pDkumHSlcMdUb+I9b+3j8R6ivoqN
TI1ned5K1uq3FyZpD0dZQWuunVeqYXuUQw5y5GxvK7haohbVpUG6lC3qYq2ubiYC
D0ENUfNoQwKBgEGucOozZCzWsJVEykL4JkWGfWPscZQlV5l+jkwNmNCVYRY4a+LJ
/fJJgN58HeXo8ePOcQkiFMJCr9AG1JSS5CXke6VFencU4+sG45jOfBY2WrQ/ZLyv
JwSqXIPdlGBEQ4+5fN4nLSEzUteKpij7KzaNae09NBWRdY0fUdvG6XdZAoGAf02S
/TfKsB97JlmEU2aqOcdj+WjC4JMG/8j2JVoRbM1U6Rb5X4qXrD7DgeKAGnWteBJP
tmjmXXvDb1O19xArlv/N9WRiJAI6FvwPkPiNUvlLsz51m9uzjZgCLzqCE9cJR91/
erQT9ORBs7n7fTsfah+sZlA2u65ecF4mGHbwmccCgYAqHNRHnx1iHrYfr97cmXc9
fNjJ7e1NHhVdgpGjaOiBSKj2rHNRy6iwCNbs5wjmRWlgqnFEM5r0VfFn9L0PvcQK
7iExMTm/PkSqHUntpy82Q8zRWmhw0G5p9DYyIPtaeW1NIKpIlCw6dTlf750BiGkr
mhBKvYQc85gja0s1c+1VXA==
-----END PRIVATE KEY-----
''';
class MyHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(
(context ?? SecurityContext())..setTrustedCertificatesBytes(certificate.codeUnits),
);
}
}
Future<void> main() async {
HttpOverrides.global = MyHttpOverrides();
final SecurityContext serverContext = SecurityContext()
..useCertificateChainBytes(certificate.codeUnits)
..usePrivateKeyBytes(privateKey.codeUnits);
final HttpServer httpServer =
await HttpServer.bindSecure('localhost', 0, serverContext);
final int port = httpServer.port;
debugPrint('Listening on port $port.');
// Initializes bindings before using any platform channels.
WidgetsFlutterBinding.ensureInitialized();
final ByteData byteData = await rootBundle.load('images/coast.jpg');
httpServer.listen((HttpRequest request) async {
const int chunk_size = 2048;
int offset = byteData.offsetInBytes;
while (offset < byteData.lengthInBytes) {
final int length = min(byteData.lengthInBytes - offset, chunk_size);
final Uint8List bytes = byteData.buffer.asUint8List(offset, length);
offset += length;
request.response.add(bytes);
// Let other isolates and microtasks to run.
await Future<void>.delayed(Duration.zero);
}
request.response.close();
});
runApp(MyApp(port));
}
const int images = 50;
@immutable
class MyApp extends StatelessWidget {
const MyApp(this.port, {super.key});
final int port;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page', port: port),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title, required this.port});
final String title;
final int port;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
Widget createImage(final int index, final Completer<bool> completer) {
return Image.network(
'https://localhost:${widget.port}/${_counter * images + index}',
frameBuilder: (
BuildContext context,
Widget child,
int? frame,
bool wasSynchronouslyLoaded,
) {
if (frame == 0 && !completer.isCompleted) {
completer.complete(true);
}
return child;
},
);
}
@override
Widget build(BuildContext context) {
final List<AnimationController> controllers = <AnimationController>[
for (int i = 0; i < images; i++)
AnimationController(
duration: const Duration(milliseconds: 3600),
vsync: this,
)..repeat(),
];
final List<Completer<bool>> completers = <Completer<bool>>[
for (int i = 0; i < images; i++)
Completer<bool>(),
];
final List<Future<bool>> futures = completers.map(
(Completer<bool> completer) => completer.future,
).toList();
final DateTime started = DateTime.now();
Future.wait(futures).then((_) {
debugPrint(
'===image_list=== all loaded in ${DateTime.now().difference(started).inMilliseconds}ms.',
);
});
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(children: createImageList(images, completers, controllers)),
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
List<Widget> createImageList(
int count,
List<Completer<bool>> completers,
List<AnimationController> controllers,
) {
final List<Widget> list = <Widget>[];
for (int i = 0; i < count; i++) {
list.add(Flexible(
fit: FlexFit.tight,
flex: i + 1,
child: RotationTransition(
turns: controllers[i],
child: createImage(i + 1, completers[i]),
),
));
}
return list;
}
}
| flutter/examples/image_list/lib/main.dart/0 | {
"file_path": "flutter/examples/image_list/lib/main.dart",
"repo_id": "flutter",
"token_count": 4257
} | 606 |
#include "ephemeral/Flutter-Generated.xcconfig"
| flutter/examples/layers/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "flutter/examples/layers/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "flutter",
"token_count": 19
} | 607 |
{
"_id": "57112806d874e9e6df7099d4",
"index": 0,
"guid": "77dc6167-2351-4a64-a603-aceaff115432",
"isActive": false,
"balance": "$1,316.41",
"picture": "http://placehold.it/32x32",
"age": 21,
"eyeColor": "brown",
"name": "Marta Hartman",
"gender": "female",
"company": "EXAMPLE",
"email": "[email protected]",
"phone": "+1 (555) 555-2328",
"address": "463 Temple Court, Brandywine, Kansas, 1113",
"about": "Incididunt commodo sunt commodo nulla adipisicing duis aute enim aute minim reprehenderit aute consectetur. Eu laborum esse aute laborum aute. Tempor in cillum exercitation aliqua velit quis incididunt esse ea nisi. Cillum pariatur reprehenderit est nisi nisi exercitation.\r\n",
"registered": "2014-01-18T12:32:22 +08:00",
"latitude": 4.101477,
"longitude": 39.153115,
"tags": [
"pariatur",
"sit",
"sint",
"ex",
"minim",
"veniam",
"ullamco"
],
"friends": [
{
"id": 0,
"name": "Tricia Guerra"
},
{
"id": 1,
"name": "Paula Dillard"
},
{
"id": 2,
"name": "Ursula Stout"
}
],
"greeting": "Hello, Marta Hartman! You have 4 unread messages.",
"favoriteFruit": "strawberry"
}
| flutter/examples/layers/services/data.json/0 | {
"file_path": "flutter/examples/layers/services/data.json",
"repo_id": "flutter",
"token_count": 557
} | 608 |
// Copyright 2014 The Flutter 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' as math;
import 'package:flutter/material.dart';
import '../rendering/src/sector_layout.dart';
RenderBoxToRenderSectorAdapter initCircle() {
return RenderBoxToRenderSectorAdapter(
innerRadius: 25.0,
child: RenderSectorRing(),
);
}
class SectorApp extends StatefulWidget {
const SectorApp({super.key});
@override
SectorAppState createState() => SectorAppState();
}
class SectorAppState extends State<SectorApp> {
final RenderBoxToRenderSectorAdapter sectors = initCircle();
final math.Random rand = math.Random(1);
List<double> wantedSectorSizes = <double>[];
List<double> actualSectorSizes = <double>[];
double get currentTheta => wantedSectorSizes.fold<double>(0.0, (double total, double value) => total + value);
void addSector() {
final double currentTheta = this.currentTheta;
if (currentTheta < kTwoPi) {
double deltaTheta;
if (currentTheta >= kTwoPi - (math.pi * 0.2 + 0.05)) {
deltaTheta = kTwoPi - currentTheta;
} else {
deltaTheta = math.pi * rand.nextDouble() / 5.0 + 0.05;
}
wantedSectorSizes.add(deltaTheta);
updateEnabledState();
}
}
void removeSector() {
if (wantedSectorSizes.isNotEmpty) {
wantedSectorSizes.removeLast();
updateEnabledState();
}
}
void doUpdates() {
int index = 0;
while (index < actualSectorSizes.length && index < wantedSectorSizes.length && actualSectorSizes[index] == wantedSectorSizes[index]) {
index += 1;
}
final RenderSectorRing ring = sectors.child! as RenderSectorRing;
while (index < actualSectorSizes.length) {
ring.remove(ring.lastChild!);
actualSectorSizes.removeLast();
}
while (index < wantedSectorSizes.length) {
final Color color = Color(((0xFF << 24) + rand.nextInt(0xFFFFFF)) | 0x808080);
ring.add(RenderSolidColor(color, desiredDeltaTheta: wantedSectorSizes[index]));
actualSectorSizes.add(wantedSectorSizes[index]);
index += 1;
}
}
static RenderBoxToRenderSectorAdapter initSector(Color color) {
final RenderSectorRing ring = RenderSectorRing(padding: 1.0);
ring.add(RenderSolidColor(const Color(0xFF909090), desiredDeltaTheta: kTwoPi * 0.15));
ring.add(RenderSolidColor(const Color(0xFF909090), desiredDeltaTheta: kTwoPi * 0.15));
ring.add(RenderSolidColor(color, desiredDeltaTheta: kTwoPi * 0.2));
return RenderBoxToRenderSectorAdapter(
innerRadius: 5.0,
child: ring,
);
}
RenderBoxToRenderSectorAdapter sectorAddIcon = initSector(const Color(0xFF00DD00));
RenderBoxToRenderSectorAdapter sectorRemoveIcon = initSector(const Color(0xFFDD0000));
bool _enabledAdd = true;
bool _enabledRemove = false;
void updateEnabledState() {
setState(() {
_enabledAdd = currentTheta < kTwoPi;
_enabledRemove = wantedSectorSizes.isNotEmpty;
});
}
void recursivelyDisposeChildren(RenderObject parent) {
parent.visitChildren((RenderObject child) {
recursivelyDisposeChildren(child);
child.dispose();
});
}
Widget buildBody() {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 25.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ElevatedButton(
onPressed: _enabledAdd ? addSector : null,
child: IntrinsicWidth(
child: Row(
children: <Widget>[
Container(
padding: const EdgeInsets.all(4.0),
margin: const EdgeInsets.only(right: 10.0),
child: WidgetToRenderBoxAdapter(
renderBox: sectorAddIcon,
onUnmount: () {
recursivelyDisposeChildren(sectorAddIcon);
},
),
),
const Text('ADD SECTOR'),
],
),
),
),
ElevatedButton(
onPressed: _enabledRemove ? removeSector : null,
child: IntrinsicWidth(
child: Row(
children: <Widget>[
Container(
padding: const EdgeInsets.all(4.0),
margin: const EdgeInsets.only(right: 10.0),
child: WidgetToRenderBoxAdapter(
renderBox: sectorRemoveIcon,
onUnmount: () {
recursivelyDisposeChildren(sectorRemoveIcon);
},
),
),
const Text('REMOVE SECTOR'),
],
),
),
),
],
),
),
Expanded(
child: Container(
margin: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(),
),
padding: const EdgeInsets.all(8.0),
child: WidgetToRenderBoxAdapter(
renderBox: sectors,
onBuild: doUpdates,
onUnmount: () {
recursivelyDisposeChildren(sectors);
},
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
title: 'Sector Layout',
home: Scaffold(
appBar: AppBar(
title: const Text('Sector Layout in a Widget Tree'),
),
body: buildBody(),
),
);
}
}
void main() {
runApp(const SectorApp());
}
| flutter/examples/layers/widgets/sectors.dart/0 | {
"file_path": "flutter/examples/layers/widgets/sectors.dart",
"repo_id": "flutter",
"token_count": 2884
} | 609 |
#include "Generated.xcconfig"
| flutter/examples/platform_channel/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/examples/platform_channel/ios/Flutter/Release.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 610 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| flutter/examples/platform_channel/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "flutter/examples/platform_channel/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 611 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter_window.h"
#include <flutter/event_channel.h>
#include <flutter/event_sink.h>
#include <flutter/event_stream_handler_functions.h>
#include <flutter/method_channel.h>
#include <flutter/standard_method_codec.h>
#include <windows.h>
#include <memory>
#include <optional>
#include "flutter/generated_plugin_registrant.h"
static constexpr int kBatteryError = -1;
static constexpr int kNoBattery = -2;
static int GetBatteryLevel() {
SYSTEM_POWER_STATUS status;
if (GetSystemPowerStatus(&status) == 0) {
return kBatteryError;
} else if (status.BatteryFlag == 128) {
return kNoBattery;
} else if (status.BatteryLifePercent == 255) {
return kBatteryError;
}
return status.BatteryLifePercent;
}
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
: project_(project) {}
FlutterWindow::~FlutterWindow() {
if (power_notification_handle_) {
UnregisterPowerSettingNotification(power_notification_handle_);
}
}
bool FlutterWindow::OnCreate() {
if (!Win32Window::OnCreate()) {
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
flutter::MethodChannel<> channel(
flutter_controller_->engine()->messenger(), "samples.flutter.io/battery",
&flutter::StandardMethodCodec::GetInstance());
channel.SetMethodCallHandler(
[](const flutter::MethodCall<>& call,
std::unique_ptr<flutter::MethodResult<>> result) {
if (call.method_name() == "getBatteryLevel") {
int battery_level = GetBatteryLevel();
if (battery_level == kBatteryError) {
result->Error("UNAVAILABLE", "Battery level not available.");
} else if (battery_level == kNoBattery) {
result->Error("NO_BATTERY", "Device does not have a battery.");
} else {
result->Success(battery_level);
}
} else {
result->NotImplemented();
}
});
flutter::EventChannel<> charging_channel(
flutter_controller_->engine()->messenger(), "samples.flutter.io/charging",
&flutter::StandardMethodCodec::GetInstance());
charging_channel.SetStreamHandler(
std::make_unique<flutter::StreamHandlerFunctions<>>(
[this](auto arguments, auto events) {
this->OnStreamListen(std::move(events));
return nullptr;
},
[this](auto arguments) {
this->OnStreamCancel();
return nullptr;
}));
SetChildContent(flutter_controller_->view()->GetNativeWindow());
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional<LRESULT> result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result) {
return *result;
}
}
switch (message) {
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
case WM_POWERBROADCAST:
SendBatteryStateEvent();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}
void FlutterWindow::OnStreamListen(
std::unique_ptr<flutter::EventSink<>>&& events) {
event_sink_ = std::move(events);
SendBatteryStateEvent();
power_notification_handle_ =
RegisterPowerSettingNotification(GetHandle(), &GUID_ACDC_POWER_SOURCE, 0);
}
void FlutterWindow::OnStreamCancel() { event_sink_ = nullptr; }
void FlutterWindow::SendBatteryStateEvent() {
SYSTEM_POWER_STATUS status;
if (GetSystemPowerStatus(&status) == 0 || status.ACLineStatus == 255) {
event_sink_->Error("UNAVAILABLE", "Charging status unavailable");
} else {
event_sink_->Success(flutter::EncodableValue(
status.ACLineStatus == 1 ? "charging" : "discharging"));
}
}
| flutter/examples/platform_channel/windows/runner/flutter_window.cpp/0 | {
"file_path": "flutter/examples/platform_channel/windows/runner/flutter_window.cpp",
"repo_id": "flutter",
"token_count": 1909
} | 612 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.examples.platform_view;
import android.content.Intent;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.io/platform_view";
private static final String METHOD_SWITCH_VIEW = "switchView";
private static final int COUNT_REQUEST = 1;
private MethodChannel.Result result;
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
MainActivity.this.result = result;
int count = methodCall.arguments();
if (methodCall.method.equals(METHOD_SWITCH_VIEW)) {
onLaunchFullScreen(count);
} else {
result.notImplemented();
}
}
}
);
}
private void onLaunchFullScreen(int count) {
Intent fullScreenIntent = new Intent(this, CountActivity.class);
fullScreenIntent.putExtra(CountActivity.EXTRA_COUNTER, count);
startActivityForResult(fullScreenIntent, COUNT_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == COUNT_REQUEST) {
if (resultCode == RESULT_OK) {
result.success(data.getIntExtra(CountActivity.EXTRA_COUNTER, 0));
} else {
result.error("ACTIVITY_FAILURE", "Failed while launching activity", null);
}
}
}
}
| flutter/examples/platform_view/android/app/src/main/java/io/flutter/examples/platform_view/MainActivity.java/0 | {
"file_path": "flutter/examples/platform_view/android/app/src/main/java/io/flutter/examples/platform_view/MainActivity.java",
"repo_id": "flutter",
"token_count": 704
} | 613 |
// Copyright 2014 The Flutter 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 <UIKit/UIKit.h>
@protocol PlatformViewControllerDelegate <NSObject>
- (void)didUpdateCounter:(int)counter;
@end
@interface PlatformViewController : UIViewController
@property(weak, nonatomic) IBOutlet UIButton* incrementButton;
@property(strong, nonatomic) id<PlatformViewControllerDelegate> delegate;
@property int counter;
@end
| flutter/examples/platform_view/ios/Runner/PlatformViewController.h/0 | {
"file_path": "flutter/examples/platform_view/ios/Runner/PlatformViewController.h",
"repo_id": "flutter",
"token_count": 142
} | 614 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:splash/main.dart' as entrypoint;
void main() {
testWidgets('Displays flutter logo and message', (WidgetTester tester) async {
entrypoint.main();
expect(find.byType(FlutterLogo), findsOneWidget);
expect(find.text('This app is only meant to be run under the Flutter debugger'), findsOneWidget);
});
}
| flutter/examples/splash/test/splash_test.dart/0 | {
"file_path": "flutter/examples/splash/test/splash_test.dart",
"repo_id": "flutter",
"token_count": 183
} | 615 |
# Copyright 2014 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# For details regarding the *Flutter Fix* feature, see
# https://flutter.dev/docs/development/tools/flutter-fix
# Please add new fixes to the top of the file, separated by one blank line
# from other fixes. In a comment, include a link to the PR where the change
# requiring the fix was made.
# Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md
# file for instructions on testing these data driven fixes.
# For documentation about this file format, see
# https://dart.dev/go/data-driven-fixes.
# * Fixes in this file are for the MaterialState enum and classes from the Material library. *
# For fixes to
# * AppBar: fix_app_bar.yaml
# * AppBarTheme: fix_app_bar_theme.yaml
# * ColorScheme: fix_color_scheme.yaml
# * Material (general): fix_material.yaml
# * SliverAppBar: fix_sliver_app_bar.yaml
# * TextTheme: fix_text_theme.yaml
# * ThemeDate: fix_theme_data.yaml
version: 1
transforms:
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetState'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
enum: 'MaterialState'
changes:
- kind: 'rename'
newName: 'WidgetState'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetPropertyResolver'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
typedef: 'MaterialPropertyResolver'
changes:
- kind: 'rename'
newName: 'WidgetPropertyResolver'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateColor'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateColor'
changes:
- kind: 'rename'
newName: 'WidgetStateColor'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateMouseCursor'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateMouseCursor'
changes:
- kind: 'rename'
newName: 'WidgetStateMouseCursor'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateBorderSide'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateBorderSide'
changes:
- kind: 'rename'
newName: 'WidgetStateBorderSide'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateOutlinedBorder'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateOutlinedBorder'
changes:
- kind: 'rename'
newName: 'WidgetStateOutlinedBorder'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateTextStyle'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateTextStyle'
changes:
- kind: 'rename'
newName: 'WidgetStateTextStyle'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateProperty'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateProperty'
changes:
- kind: 'rename'
newName: 'WidgetStateProperty'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStatePropertyAll'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStatePropertyAll'
changes:
- kind: 'rename'
newName: 'WidgetStatePropertyAll'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStatesController'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStatesController'
changes:
- kind: 'rename'
newName: 'WidgetStatesController'
# Before adding a new fix: read instructions at the top of this file.
| flutter/packages/flutter/lib/fix_data/fix_material/fix_widget_state.yaml/0 | {
"file_path": "flutter/packages/flutter/lib/fix_data/fix_material/fix_widget_state.yaml",
"repo_id": "flutter",
"token_count": 1660
} | 616 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Flutter widgets implementing Material Design.
///
/// To use, import `package:flutter/material.dart`.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=DL0Ix1lnC4w}
///
/// See also:
///
/// * [docs.flutter.dev/ui/widgets/material](https://docs.flutter.dev/ui/widgets/material)
/// for a catalog of commonly-used Material component widgets.
/// * [m3.material.io](https://m3.material.io/) for the Material 3 specification
/// * [m2.material.io](https://m2.material.io/) for the Material 2 specification
library material;
export 'src/material/about.dart';
export 'src/material/action_buttons.dart';
export 'src/material/action_chip.dart';
export 'src/material/action_icons_theme.dart';
export 'src/material/adaptive_text_selection_toolbar.dart';
export 'src/material/animated_icons.dart';
export 'src/material/app.dart';
export 'src/material/app_bar.dart';
export 'src/material/app_bar_theme.dart';
export 'src/material/arc.dart';
export 'src/material/autocomplete.dart';
export 'src/material/badge.dart';
export 'src/material/badge_theme.dart';
export 'src/material/banner.dart';
export 'src/material/banner_theme.dart';
export 'src/material/bottom_app_bar.dart';
export 'src/material/bottom_app_bar_theme.dart';
export 'src/material/bottom_navigation_bar.dart';
export 'src/material/bottom_navigation_bar_theme.dart';
export 'src/material/bottom_sheet.dart';
export 'src/material/bottom_sheet_theme.dart';
export 'src/material/button.dart';
export 'src/material/button_bar.dart';
export 'src/material/button_bar_theme.dart';
export 'src/material/button_style.dart';
export 'src/material/button_style_button.dart';
export 'src/material/button_theme.dart';
export 'src/material/calendar_date_picker.dart';
export 'src/material/card.dart';
export 'src/material/card_theme.dart';
export 'src/material/checkbox.dart';
export 'src/material/checkbox_list_tile.dart';
export 'src/material/checkbox_theme.dart';
export 'src/material/chip.dart';
export 'src/material/chip_theme.dart';
export 'src/material/choice_chip.dart';
export 'src/material/circle_avatar.dart';
export 'src/material/color_scheme.dart';
export 'src/material/colors.dart';
export 'src/material/constants.dart';
export 'src/material/curves.dart';
export 'src/material/data_table.dart';
export 'src/material/data_table_source.dart';
export 'src/material/data_table_theme.dart';
export 'src/material/date.dart';
export 'src/material/date_picker.dart';
export 'src/material/date_picker_theme.dart';
export 'src/material/debug.dart';
export 'src/material/desktop_text_selection.dart';
export 'src/material/desktop_text_selection_toolbar.dart';
export 'src/material/desktop_text_selection_toolbar_button.dart';
export 'src/material/dialog.dart';
export 'src/material/dialog_theme.dart';
export 'src/material/divider.dart';
export 'src/material/divider_theme.dart';
export 'src/material/drawer.dart';
export 'src/material/drawer_header.dart';
export 'src/material/drawer_theme.dart';
export 'src/material/dropdown.dart';
export 'src/material/dropdown_menu.dart';
export 'src/material/dropdown_menu_theme.dart';
export 'src/material/elevated_button.dart';
export 'src/material/elevated_button_theme.dart';
export 'src/material/elevation_overlay.dart';
export 'src/material/expand_icon.dart';
export 'src/material/expansion_panel.dart';
export 'src/material/expansion_tile.dart';
export 'src/material/expansion_tile_theme.dart';
export 'src/material/feedback.dart';
export 'src/material/filled_button.dart';
export 'src/material/filled_button_theme.dart';
export 'src/material/filter_chip.dart';
export 'src/material/flexible_space_bar.dart';
export 'src/material/floating_action_button.dart';
export 'src/material/floating_action_button_location.dart';
export 'src/material/floating_action_button_theme.dart';
export 'src/material/flutter_logo.dart';
export 'src/material/grid_tile.dart';
export 'src/material/grid_tile_bar.dart';
export 'src/material/icon_button.dart';
export 'src/material/icon_button_theme.dart';
export 'src/material/icons.dart';
export 'src/material/ink_decoration.dart';
export 'src/material/ink_highlight.dart';
export 'src/material/ink_ripple.dart';
export 'src/material/ink_sparkle.dart';
export 'src/material/ink_splash.dart';
export 'src/material/ink_well.dart';
export 'src/material/input_border.dart';
export 'src/material/input_chip.dart';
export 'src/material/input_date_picker_form_field.dart';
export 'src/material/input_decorator.dart';
export 'src/material/list_tile.dart';
export 'src/material/list_tile_theme.dart';
export 'src/material/magnifier.dart';
export 'src/material/material.dart';
export 'src/material/material_button.dart';
export 'src/material/material_localizations.dart';
export 'src/material/material_state.dart';
export 'src/material/material_state_mixin.dart';
export 'src/material/menu_anchor.dart';
export 'src/material/menu_bar_theme.dart';
export 'src/material/menu_button_theme.dart';
export 'src/material/menu_style.dart';
export 'src/material/menu_theme.dart';
export 'src/material/mergeable_material.dart';
export 'src/material/motion.dart';
export 'src/material/navigation_bar.dart';
export 'src/material/navigation_bar_theme.dart';
export 'src/material/navigation_drawer.dart';
export 'src/material/navigation_drawer_theme.dart';
export 'src/material/navigation_rail.dart';
export 'src/material/navigation_rail_theme.dart';
export 'src/material/no_splash.dart';
export 'src/material/outlined_button.dart';
export 'src/material/outlined_button_theme.dart';
export 'src/material/page.dart';
export 'src/material/page_transitions_theme.dart';
export 'src/material/paginated_data_table.dart';
export 'src/material/popup_menu.dart';
export 'src/material/popup_menu_theme.dart';
export 'src/material/progress_indicator.dart';
export 'src/material/progress_indicator_theme.dart';
export 'src/material/radio.dart';
export 'src/material/radio_list_tile.dart';
export 'src/material/radio_theme.dart';
export 'src/material/range_slider.dart';
export 'src/material/refresh_indicator.dart';
export 'src/material/reorderable_list.dart';
export 'src/material/scaffold.dart';
export 'src/material/scrollbar.dart';
export 'src/material/scrollbar_theme.dart';
export 'src/material/search.dart';
export 'src/material/search_anchor.dart';
export 'src/material/search_bar_theme.dart';
export 'src/material/search_view_theme.dart';
export 'src/material/segmented_button.dart';
export 'src/material/segmented_button_theme.dart';
export 'src/material/selectable_text.dart';
export 'src/material/selection_area.dart';
export 'src/material/shadows.dart';
export 'src/material/slider.dart';
export 'src/material/slider_theme.dart';
export 'src/material/snack_bar.dart';
export 'src/material/snack_bar_theme.dart';
export 'src/material/spell_check_suggestions_toolbar.dart';
export 'src/material/spell_check_suggestions_toolbar_layout_delegate.dart';
export 'src/material/stepper.dart';
export 'src/material/switch.dart';
export 'src/material/switch_list_tile.dart';
export 'src/material/switch_theme.dart';
export 'src/material/tab_bar_theme.dart';
export 'src/material/tab_controller.dart';
export 'src/material/tab_indicator.dart';
export 'src/material/tabs.dart';
export 'src/material/text_button.dart';
export 'src/material/text_button_theme.dart';
export 'src/material/text_field.dart';
export 'src/material/text_form_field.dart';
export 'src/material/text_selection.dart';
export 'src/material/text_selection_theme.dart';
export 'src/material/text_selection_toolbar.dart';
export 'src/material/text_selection_toolbar_text_button.dart';
export 'src/material/text_theme.dart';
export 'src/material/theme.dart';
export 'src/material/theme_data.dart';
export 'src/material/time.dart';
export 'src/material/time_picker.dart';
export 'src/material/time_picker_theme.dart';
export 'src/material/toggle_buttons.dart';
export 'src/material/toggle_buttons_theme.dart';
export 'src/material/toggleable.dart';
export 'src/material/tooltip.dart';
export 'src/material/tooltip_theme.dart';
export 'src/material/tooltip_visibility.dart';
export 'src/material/typography.dart';
export 'src/material/user_accounts_drawer_header.dart';
export 'widgets.dart';
| flutter/packages/flutter/lib/material.dart/0 | {
"file_path": "flutter/packages/flutter/lib/material.dart",
"repo_id": "flutter",
"token_count": 2907
} | 617 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'desktop_text_selection_toolbar.dart';
import 'desktop_text_selection_toolbar_button.dart';
import 'text_selection_toolbar.dart';
import 'text_selection_toolbar_button.dart';
/// The default Cupertino context menu for text selection for the current
/// platform with the given children.
///
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.platforms}
/// Builds the mobile Cupertino context menu on all mobile platforms, not just
/// iOS, and builds the desktop Cupertino context menu on all desktop platforms,
/// not just MacOS. For a widget that builds the native-looking context menu for
/// all platforms, see [AdaptiveTextSelectionToolbar].
/// {@endtemplate}
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar], which does the same thing as this widget
/// but for all platforms, not just the Cupertino-styled platforms.
/// * [CupertinoAdaptiveTextSelectionToolbar.getAdaptiveButtons], which builds
/// the Cupertino button Widgets for the current platform given
/// [ContextMenuButtonItem]s.
class CupertinoAdaptiveTextSelectionToolbar extends StatelessWidget {
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// given [children].
///
/// See also:
///
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// * [CupertinoAdaptiveTextSelectionToolbar.buttonItems], which takes a list
/// of [ContextMenuButtonItem]s instead of [children] widgets.
/// {@endtemplate}
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// * [CupertinoAdaptiveTextSelectionToolbar.editable], which builds the
/// default Cupertino children for an editable field.
/// {@endtemplate}
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
/// * [CupertinoAdaptiveTextSelectionToolbar.editableText], which builds the
/// default Cupertino children for an [EditableText].
/// {@endtemplate}
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
/// * [CupertinoAdaptiveTextSelectionToolbar.selectable], which builds the
/// Cupertino children for content that is selectable but not editable.
/// {@endtemplate}
const CupertinoAdaptiveTextSelectionToolbar({
super.key,
required this.children,
required this.anchors,
}) : buttonItems = null;
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] whose
/// children will be built from the given [buttonItems].
///
/// See also:
///
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// * [CupertinoAdaptiveTextSelectionToolbar.new], which takes the children
/// directly as a list of widgets.
/// {@endtemplate}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
const CupertinoAdaptiveTextSelectionToolbar.buttonItems({
super.key,
required this.buttonItems,
required this.anchors,
}) : children = null;
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// default children for an editable field.
///
/// If a callback is null, then its corresponding button will not be built.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.editable], which is similar to this but
/// includes Material and Cupertino toolbars.
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
CupertinoAdaptiveTextSelectionToolbar.editable({
super.key,
required ClipboardStatus clipboardStatus,
required VoidCallback? onCopy,
required VoidCallback? onCut,
required VoidCallback? onPaste,
required VoidCallback? onSelectAll,
required VoidCallback? onLookUp,
required VoidCallback? onSearchWeb,
required VoidCallback? onShare,
required VoidCallback? onLiveTextInput,
required this.anchors,
}) : children = null,
buttonItems = EditableText.getEditableButtonItems(
clipboardStatus: clipboardStatus,
onCopy: onCopy,
onCut: onCut,
onPaste: onPaste,
onSelectAll: onSelectAll,
onLookUp: onLookUp,
onSearchWeb: onSearchWeb,
onShare: onShare,
onLiveTextInput: onLiveTextInput
);
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// default children for an [EditableText].
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.editableText], which is similar to this
/// but includes Material and Cupertino toolbars.
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
CupertinoAdaptiveTextSelectionToolbar.editableText({
super.key,
required EditableTextState editableTextState,
}) : children = null,
buttonItems = editableTextState.contextMenuButtonItems,
anchors = editableTextState.contextMenuAnchors;
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// default children for selectable, but not editable, content.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.selectable], which is similar to this but
/// includes Material and Cupertino toolbars.
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
CupertinoAdaptiveTextSelectionToolbar.selectable({
super.key,
required VoidCallback onCopy,
required VoidCallback onSelectAll,
required SelectionGeometry selectionGeometry,
required this.anchors,
}) : children = null,
buttonItems = SelectableRegion.getSelectableButtonItems(
selectionGeometry: selectionGeometry,
onCopy: onCopy,
onSelectAll: onSelectAll,
onShare: null, // See https://github.com/flutter/flutter/issues/141775.
);
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.anchors}
final TextSelectionToolbarAnchors anchors;
/// The children of the toolbar, typically buttons.
final List<Widget>? children;
/// The [ContextMenuButtonItem]s that will be turned into the correct button
/// widgets for the current platform.
final List<ContextMenuButtonItem>? buttonItems;
/// Returns a List of Widgets generated by turning [buttonItems] into the
/// default context menu buttons for Cupertino on the current platform.
///
/// This is useful when building a text selection toolbar with the default
/// button appearance for the given platform, but where the toolbar and/or the
/// button actions and labels may be custom.
///
/// Does not build Material buttons. On non-Apple platforms, Cupertino buttons
/// will still be used, because the Cupertino library does not access the
/// Material library. To get the native-looking buttons on every platform,
/// use [AdaptiveTextSelectionToolbar.getAdaptiveButtons] in the Material
/// library.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.getAdaptiveButtons], which is the Material
/// equivalent of this class and builds only the Material buttons. It
/// includes a live example of using `getAdaptiveButtons`.
static Iterable<Widget> getAdaptiveButtons(BuildContext context, List<ContextMenuButtonItem> buttonItems) {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoTextSelectionToolbarButton.buttonItem(
buttonItem: buttonItem,
);
});
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.macOS:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoDesktopTextSelectionToolbarButton.buttonItem(
buttonItem: buttonItem,
);
});
}
}
@override
Widget build(BuildContext context) {
// If there aren't any buttons to build, build an empty toolbar.
if ((children?.isEmpty ?? false) || (buttonItems?.isEmpty ?? false)) {
return const SizedBox.shrink();
}
final List<Widget> resultChildren = children
?? getAdaptiveButtons(context, buttonItems!).toList();
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
return CupertinoTextSelectionToolbar(
anchorAbove: anchors.primaryAnchor,
anchorBelow: anchors.secondaryAnchor ?? anchors.primaryAnchor,
children: resultChildren,
);
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.macOS:
return CupertinoDesktopTextSelectionToolbar(
anchor: anchors.primaryAnchor,
children: resultChildren,
);
}
}
}
| flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart",
"repo_id": "flutter",
"token_count": 3229
} | 618 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'colors.dart';
import 'list_section.dart';
// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in
// iOS 14.2 SDK.
const EdgeInsetsDirectional _kFormDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 10.0);
/// An iOS-style form section.
///
/// The base constructor for [CupertinoFormSection] constructs an
/// edge-to-edge style section which includes an iOS-style header, rows,
/// the dividers between rows, and borders on top and bottom of the rows.
///
/// The [CupertinoFormSection.insetGrouped] constructor creates a round-edged and
/// padded section that is commonly seen in notched-displays like iPhone X and
/// beyond. Creates an iOS-style header, rows, and the dividers
/// between rows. Does not create borders on top and bottom of the rows.
///
/// The [header] parameter sets the form section header. The section header lies
/// above the [children] rows, with margins that match the iOS style.
///
/// The [footer] parameter sets the form section footer. The section footer
/// lies below the [children] rows.
///
/// The [children] parameter is required and sets the list of rows shown in
/// the section. The [children] parameter takes a list, as opposed to a more
/// efficient builder function that lazy builds, because forms are intended to
/// be short in row count. It is recommended that only [CupertinoFormRow] and
/// [CupertinoTextFormFieldRow] widgets be included in the [children] list in
/// order to retain the iOS look.
///
/// The [margin] parameter sets the spacing around the content area of the
/// section encapsulating [children].
///
/// The [decoration] parameter sets the decoration around [children].
/// If null, defaults to [CupertinoColors.secondarySystemGroupedBackground].
/// If null, defaults to 10.0 circular radius when constructing with
/// [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
///
/// The [backgroundColor] parameter sets the background color behind the section.
/// If null, defaults to [CupertinoColors.systemGroupedBackground].
///
/// {@macro flutter.material.Material.clipBehavior}
///
/// See also:
///
/// * [CupertinoFormRow], an iOS-style list tile, a typical child of
/// [CupertinoFormSection].
/// * [CupertinoListSection], an iOS-style list section.
class CupertinoFormSection extends StatelessWidget {
/// Creates a section that mimics standard iOS forms.
///
/// The base constructor for [CupertinoFormSection] constructs an
/// edge-to-edge style section which includes an iOS-style header,
/// rows, the dividers between rows, and borders on top and bottom of the rows.
///
/// The [header] parameter sets the form section header. The section header
/// lies above the [children] rows, with margins that match the iOS style.
///
/// The [footer] parameter sets the form section footer. The section footer
/// lies below the [children] rows.
///
/// The [children] parameter is required and sets the list of rows shown in
/// the section. The [children] parameter takes a list, as opposed to a more
/// efficient builder function that lazy builds, because forms are intended to
/// be short in row count. It is recommended that only [CupertinoFormRow] and
/// [CupertinoTextFormFieldRow] widgets be included in the [children] list in
/// order to retain the iOS look.
///
/// The [margin] parameter sets the spacing around the content area of the
/// section encapsulating [children], and defaults to zero padding.
///
/// The [decoration] parameter sets the decoration around [children].
/// If null, defaults to [CupertinoColors.secondarySystemGroupedBackground].
/// If null, defaults to 10.0 circular radius when constructing with
/// [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
///
/// The [backgroundColor] parameter sets the background color behind the
/// section. If null, defaults to [CupertinoColors.systemGroupedBackground].
///
/// {@macro flutter.material.Material.clipBehavior}
const CupertinoFormSection({
super.key,
required this.children,
this.header,
this.footer,
this.margin = EdgeInsets.zero,
this.backgroundColor = CupertinoColors.systemGroupedBackground,
this.decoration,
this.clipBehavior = Clip.none,
}) : _type = CupertinoListSectionType.base,
assert(children.length > 0);
/// Creates a section that mimics standard "Inset Grouped" iOS forms.
///
/// The [CupertinoFormSection.insetGrouped] constructor creates a round-edged and
/// padded section that is commonly seen in notched-displays like iPhone X and
/// beyond. Creates an iOS-style header, rows, and the dividers
/// between rows. Does not create borders on top and bottom of the rows.
///
/// The [header] parameter sets the form section header. The section header
/// lies above the [children] rows, with margins that match the iOS style.
///
/// The [footer] parameter sets the form section footer. The section footer
/// lies below the [children] rows.
///
/// The [children] parameter is required and sets the list of rows shown in
/// the section. The [children] parameter takes a list, as opposed to a more
/// efficient builder function that lazy builds, because forms are intended to
/// be short in row count. It is recommended that only [CupertinoFormRow] and
/// [CupertinoTextFormFieldRow] widgets be included in the [children] list in
/// order to retain the iOS look.
///
/// The [margin] parameter sets the spacing around the content area of the
/// section encapsulating [children], and defaults to the standard
/// notched-style iOS form padding.
///
/// The [decoration] parameter sets the decoration around [children].
/// If null, defaults to [CupertinoColors.secondarySystemGroupedBackground].
/// If null, defaults to 10.0 circular radius when constructing with
/// [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
///
/// The [backgroundColor] parameter sets the background color behind the
/// section. If null, defaults to [CupertinoColors.systemGroupedBackground].
///
/// {@macro flutter.material.Material.clipBehavior}
const CupertinoFormSection.insetGrouped({
super.key,
required this.children,
this.header,
this.footer,
this.margin = _kFormDefaultInsetGroupedRowsMargin,
this.backgroundColor = CupertinoColors.systemGroupedBackground,
this.decoration,
this.clipBehavior = Clip.none,
}) : _type = CupertinoListSectionType.insetGrouped,
assert(children.length > 0);
final CupertinoListSectionType _type;
/// Sets the form section header. The section header lies above the
/// [children] rows.
final Widget? header;
/// Sets the form section footer. The section footer lies below the
/// [children] rows.
final Widget? footer;
/// Margin around the content area of the section encapsulating [children].
///
/// Defaults to zero padding if constructed with standard
/// [CupertinoFormSection] constructor. Defaults to the standard notched-style
/// iOS margin when constructing with [CupertinoFormSection.insetGrouped].
final EdgeInsetsGeometry margin;
/// The list of rows in the section.
///
/// This takes a list, as opposed to a more efficient builder function that
/// lazy builds, because forms are intended to be short in row count. It is
/// recommended that only [CupertinoFormRow] and [CupertinoTextFormFieldRow]
/// widgets be included in the [children] list in order to retain the iOS look.
final List<Widget> children;
/// Sets the decoration around [children].
///
/// If null, background color defaults to
/// [CupertinoColors.secondarySystemGroupedBackground].
///
/// If null, border radius defaults to 10.0 circular radius when constructing
/// with [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
final BoxDecoration? decoration;
/// Sets the background color behind the section.
///
/// Defaults to [CupertinoColors.systemGroupedBackground].
final Color backgroundColor;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
@override
Widget build(BuildContext context) {
final Widget? headerWidget = header == null
? null
: DefaultTextStyle(
style: TextStyle(
fontSize: 13.0,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
child: header!);
final Widget? footerWidget = footer == null
? null
: DefaultTextStyle(
style: TextStyle(
fontSize: 13.0,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
child: footer!);
switch (_type) {
case CupertinoListSectionType.base:
return CupertinoListSection(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
case CupertinoListSectionType.insetGrouped:
return CupertinoListSection.insetGrouped(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
}
}
}
| flutter/packages/flutter/lib/src/cupertino/form_section.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/form_section.dart",
"repo_id": "flutter",
"token_count": 3001
} | 619 |
// Copyright 2014 The Flutter 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:collection';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
// Minimum padding from edges of the segmented control to edges of
// encompassing widget.
const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(horizontal: 16.0);
// Minimum height of the segmented control.
const double _kMinSegmentedControlHeight = 28.0;
// The duration of the fade animation used to transition when a new widget
// is selected.
const Duration _kFadeDuration = Duration(milliseconds: 165);
/// An iOS-style segmented control.
///
/// Displays the widgets provided in the [Map] of [children] in a
/// horizontal list. Used to select between a number of mutually exclusive
/// options. When one option in the segmented control is selected, the other
/// options in the segmented control cease to be selected.
///
/// A segmented control can feature any [Widget] as one of the values in its
/// [Map] of [children]. The type T is the type of the keys used
/// to identify each widget and determine which widget is selected. As
/// required by the [Map] class, keys must be of consistent types
/// and must be comparable. The ordering of the keys will determine the order
/// of the widgets in the segmented control.
///
/// When the state of the segmented control changes, the widget calls the
/// [onValueChanged] callback. The map key associated with the newly selected
/// widget is returned in the [onValueChanged] callback. Typically, widgets
/// that use a segmented control will listen for the [onValueChanged] callback
/// and rebuild the segmented control with a new [groupValue] to update which
/// option is currently selected.
///
/// The [children] will be displayed in the order of the keys in the [Map].
/// The height of the segmented control is determined by the height of the
/// tallest widget provided as a value in the [Map] of [children].
/// The width of each child in the segmented control will be equal to the width
/// of widest child, unless the combined width of the children is wider than
/// the available horizontal space. In this case, the available horizontal space
/// is divided by the number of provided [children] to determine the width of
/// each widget. The selection area for each of the widgets in the [Map] of
/// [children] will then be expanded to fill the calculated space, so each
/// widget will appear to have the same dimensions.
///
/// A segmented control may optionally be created with custom colors. The
/// [unselectedColor], [selectedColor], [borderColor], and [pressedColor]
/// arguments can be used to override the segmented control's colors from
/// [CupertinoTheme] defaults.
///
/// {@tool dartpad}
/// This example shows a [CupertinoSegmentedControl] with an enum type.
///
/// The callback provided to [onValueChanged] should update the state of
/// the parent [StatefulWidget] using the [State.setState] method, so that
/// the parent gets rebuilt; for example:
///
/// ** See code in examples/api/lib/cupertino/segmented_control/cupertino_segmented_control.0.dart **
/// {@end-tool}
/// See also:
///
/// * [CupertinoSegmentedControl], a segmented control widget in the style used
/// up until iOS 13.
/// * <https://developer.apple.com/design/human-interface-guidelines/ios/controls/segmented-controls/>
class CupertinoSegmentedControl<T extends Object> extends StatefulWidget {
/// Creates an iOS-style segmented control bar.
///
/// The [children] argument must be an ordered [Map] such as a
/// [LinkedHashMap]. Further, the length of the [children] list must be
/// greater than one.
///
/// Each widget value in the map of [children] must have an associated key
/// that uniquely identifies this widget. This key is what will be returned
/// in the [onValueChanged] callback when a new value from the [children] map
/// is selected.
///
/// The [groupValue] is the currently selected value for the segmented control.
/// If no [groupValue] is provided, or the [groupValue] is null, no widget will
/// appear as selected. The [groupValue] must be either null or one of the keys
/// in the [children] map.
CupertinoSegmentedControl({
super.key,
required this.children,
required this.onValueChanged,
this.groupValue,
this.unselectedColor,
this.selectedColor,
this.borderColor,
this.pressedColor,
this.padding,
}) : assert(children.length >= 2),
assert(
groupValue == null || children.keys.any((T child) => child == groupValue),
'The groupValue must be either null or one of the keys in the children map.',
);
/// The identifying keys and corresponding widget values in the
/// segmented control.
///
/// The map must have more than one entry.
/// This attribute must be an ordered [Map] such as a [LinkedHashMap].
final Map<T, Widget> children;
/// The identifier of the widget that is currently selected.
///
/// This must be one of the keys in the [Map] of [children].
/// If this attribute is null, no widget will be initially selected.
final T? groupValue;
/// The callback that is called when a new option is tapped.
///
/// The segmented control passes the newly selected widget's associated key
/// to the callback but does not actually change state until the parent
/// widget rebuilds the segmented control with the new [groupValue].
final ValueChanged<T> onValueChanged;
/// The color used to fill the backgrounds of unselected widgets and as the
/// text color of the selected widget.
///
/// Defaults to [CupertinoTheme]'s `primaryContrastingColor` if null.
final Color? unselectedColor;
/// The color used to fill the background of the selected widget and as the text
/// color of unselected widgets.
///
/// Defaults to [CupertinoTheme]'s `primaryColor` if null.
final Color? selectedColor;
/// The color used as the border around each widget.
///
/// Defaults to [CupertinoTheme]'s `primaryColor` if null.
final Color? borderColor;
/// The color used to fill the background of the widget the user is
/// temporarily interacting with through a long press or drag.
///
/// Defaults to the selectedColor at 20% opacity if null.
final Color? pressedColor;
/// The CupertinoSegmentedControl will be placed inside this padding.
///
/// Defaults to EdgeInsets.symmetric(horizontal: 16.0)
final EdgeInsetsGeometry? padding;
@override
State<CupertinoSegmentedControl<T>> createState() => _SegmentedControlState<T>();
}
class _SegmentedControlState<T extends Object> extends State<CupertinoSegmentedControl<T>>
with TickerProviderStateMixin<CupertinoSegmentedControl<T>> {
T? _pressedKey;
final List<AnimationController> _selectionControllers = <AnimationController>[];
final List<ColorTween> _childTweens = <ColorTween>[];
late ColorTween _forwardBackgroundColorTween;
late ColorTween _reverseBackgroundColorTween;
late ColorTween _textColorTween;
Color? _selectedColor;
Color? _unselectedColor;
Color? _borderColor;
Color? _pressedColor;
AnimationController createAnimationController() {
return AnimationController(
duration: _kFadeDuration,
vsync: this,
)..addListener(() {
setState(() {
// State of background/text colors has changed
});
});
}
bool _updateColors() {
assert(mounted, 'This should only be called after didUpdateDependencies');
bool changed = false;
final Color selectedColor = widget.selectedColor ?? CupertinoTheme.of(context).primaryColor;
if (_selectedColor != selectedColor) {
changed = true;
_selectedColor = selectedColor;
}
final Color unselectedColor = widget.unselectedColor ?? CupertinoTheme.of(context).primaryContrastingColor;
if (_unselectedColor != unselectedColor) {
changed = true;
_unselectedColor = unselectedColor;
}
final Color borderColor = widget.borderColor ?? CupertinoTheme.of(context).primaryColor;
if (_borderColor != borderColor) {
changed = true;
_borderColor = borderColor;
}
final Color pressedColor = widget.pressedColor ?? CupertinoTheme.of(context).primaryColor.withOpacity(0.2);
if (_pressedColor != pressedColor) {
changed = true;
_pressedColor = pressedColor;
}
_forwardBackgroundColorTween = ColorTween(
begin: _pressedColor,
end: _selectedColor,
);
_reverseBackgroundColorTween = ColorTween(
begin: _unselectedColor,
end: _selectedColor,
);
_textColorTween = ColorTween(
begin: _selectedColor,
end: _unselectedColor,
);
return changed;
}
void _updateAnimationControllers() {
assert(mounted, 'This should only be called after didUpdateDependencies');
for (final AnimationController controller in _selectionControllers) {
controller.dispose();
}
_selectionControllers.clear();
_childTweens.clear();
for (final T key in widget.children.keys) {
final AnimationController animationController = createAnimationController();
if (widget.groupValue == key) {
_childTweens.add(_reverseBackgroundColorTween);
animationController.value = 1.0;
} else {
_childTweens.add(_forwardBackgroundColorTween);
}
_selectionControllers.add(animationController);
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_updateColors()) {
_updateAnimationControllers();
}
}
@override
void didUpdateWidget(CupertinoSegmentedControl<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (_updateColors() || oldWidget.children.length != widget.children.length) {
_updateAnimationControllers();
}
if (oldWidget.groupValue != widget.groupValue) {
int index = 0;
for (final T key in widget.children.keys) {
if (widget.groupValue == key) {
_childTweens[index] = _forwardBackgroundColorTween;
_selectionControllers[index].forward();
} else {
_childTweens[index] = _reverseBackgroundColorTween;
_selectionControllers[index].reverse();
}
index += 1;
}
}
}
@override
void dispose() {
for (final AnimationController animationController in _selectionControllers) {
animationController.dispose();
}
super.dispose();
}
void _onTapDown(T currentKey) {
if (_pressedKey == null && currentKey != widget.groupValue) {
setState(() {
_pressedKey = currentKey;
});
}
}
void _onTapCancel() {
setState(() {
_pressedKey = null;
});
}
void _onTap(T currentKey) {
if (currentKey != _pressedKey) {
return;
}
if (currentKey != widget.groupValue) {
widget.onValueChanged(currentKey);
}
_pressedKey = null;
}
Color? getTextColor(int index, T currentKey) {
if (_selectionControllers[index].isAnimating) {
return _textColorTween.evaluate(_selectionControllers[index]);
}
if (widget.groupValue == currentKey) {
return _unselectedColor;
}
return _selectedColor;
}
Color? getBackgroundColor(int index, T currentKey) {
if (_selectionControllers[index].isAnimating) {
return _childTweens[index].evaluate(_selectionControllers[index]);
}
if (widget.groupValue == currentKey) {
return _selectedColor;
}
if (_pressedKey == currentKey) {
return _pressedColor;
}
return _unselectedColor;
}
@override
Widget build(BuildContext context) {
final List<Widget> gestureChildren = <Widget>[];
final List<Color> backgroundColors = <Color>[];
int index = 0;
int? selectedIndex;
int? pressedIndex;
for (final T currentKey in widget.children.keys) {
selectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex;
pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex;
final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith(
color: getTextColor(index, currentKey),
);
final IconThemeData iconTheme = IconThemeData(
color: getTextColor(index, currentKey),
);
Widget child = Center(
child: widget.children[currentKey],
);
child = MouseRegion(
cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails event) {
_onTapDown(currentKey);
},
onTapCancel: _onTapCancel,
onTap: () {
_onTap(currentKey);
},
child: IconTheme(
data: iconTheme,
child: DefaultTextStyle(
style: textStyle,
child: Semantics(
button: true,
inMutuallyExclusiveGroup: true,
selected: widget.groupValue == currentKey,
child: child,
),
),
),
),
);
backgroundColors.add(getBackgroundColor(index, currentKey)!);
gestureChildren.add(child);
index += 1;
}
final Widget box = _SegmentedControlRenderWidget<T>(
selectedIndex: selectedIndex,
pressedIndex: pressedIndex,
backgroundColors: backgroundColors,
borderColor: _borderColor!,
children: gestureChildren,
);
return Padding(
padding: widget.padding ?? _kHorizontalItemPadding,
child: UnconstrainedBox(
constrainedAxis: Axis.horizontal,
child: box,
),
);
}
}
class _SegmentedControlRenderWidget<T> extends MultiChildRenderObjectWidget {
const _SegmentedControlRenderWidget({
super.key,
super.children,
required this.selectedIndex,
required this.pressedIndex,
required this.backgroundColors,
required this.borderColor,
});
final int? selectedIndex;
final int? pressedIndex;
final List<Color> backgroundColors;
final Color borderColor;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderSegmentedControl<T>(
textDirection: Directionality.of(context),
selectedIndex: selectedIndex,
pressedIndex: pressedIndex,
backgroundColors: backgroundColors,
borderColor: borderColor,
);
}
@override
void updateRenderObject(BuildContext context, _RenderSegmentedControl<T> renderObject) {
renderObject
..textDirection = Directionality.of(context)
..selectedIndex = selectedIndex
..pressedIndex = pressedIndex
..backgroundColors = backgroundColors
..borderColor = borderColor;
}
}
class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData<RenderBox> {
RRect? surroundingRect;
}
typedef _NextChild = RenderBox? Function(RenderBox child);
class _RenderSegmentedControl<T> extends RenderBox
with ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,
RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {
_RenderSegmentedControl({
required int? selectedIndex,
required int? pressedIndex,
required TextDirection textDirection,
required List<Color> backgroundColors,
required Color borderColor,
}) : _textDirection = textDirection,
_selectedIndex = selectedIndex,
_pressedIndex = pressedIndex,
_backgroundColors = backgroundColors,
_borderColor = borderColor;
int? get selectedIndex => _selectedIndex;
int? _selectedIndex;
set selectedIndex(int? value) {
if (_selectedIndex == value) {
return;
}
_selectedIndex = value;
markNeedsPaint();
}
int? get pressedIndex => _pressedIndex;
int? _pressedIndex;
set pressedIndex(int? value) {
if (_pressedIndex == value) {
return;
}
_pressedIndex = value;
markNeedsPaint();
}
TextDirection get textDirection => _textDirection;
TextDirection _textDirection;
set textDirection(TextDirection value) {
if (_textDirection == value) {
return;
}
_textDirection = value;
markNeedsLayout();
}
List<Color> get backgroundColors => _backgroundColors;
List<Color> _backgroundColors;
set backgroundColors(List<Color> value) {
if (_backgroundColors == value) {
return;
}
_backgroundColors = value;
markNeedsPaint();
}
Color get borderColor => _borderColor;
Color _borderColor;
set borderColor(Color value) {
if (_borderColor == value) {
return;
}
_borderColor = value;
markNeedsPaint();
}
@override
double computeMinIntrinsicWidth(double height) {
RenderBox? child = firstChild;
double minWidth = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childWidth = child.getMinIntrinsicWidth(height);
minWidth = math.max(minWidth, childWidth);
child = childParentData.nextSibling;
}
return minWidth * childCount;
}
@override
double computeMaxIntrinsicWidth(double height) {
RenderBox? child = firstChild;
double maxWidth = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childWidth = child.getMaxIntrinsicWidth(height);
maxWidth = math.max(maxWidth, childWidth);
child = childParentData.nextSibling;
}
return maxWidth * childCount;
}
@override
double computeMinIntrinsicHeight(double width) {
RenderBox? child = firstChild;
double minHeight = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childHeight = child.getMinIntrinsicHeight(width);
minHeight = math.max(minHeight, childHeight);
child = childParentData.nextSibling;
}
return minHeight;
}
@override
double computeMaxIntrinsicHeight(double width) {
RenderBox? child = firstChild;
double maxHeight = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childHeight = child.getMaxIntrinsicHeight(width);
maxHeight = math.max(maxHeight, childHeight);
child = childParentData.nextSibling;
}
return maxHeight;
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
@override
void setupParentData(RenderBox child) {
if (child.parentData is! _SegmentedControlContainerBoxParentData) {
child.parentData = _SegmentedControlContainerBoxParentData();
}
}
void _layoutRects(_NextChild nextChild, RenderBox? leftChild, RenderBox? rightChild) {
RenderBox? child = leftChild;
double start = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final Offset childOffset = Offset(start, 0.0);
childParentData.offset = childOffset;
final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height);
final RRect rChildRect;
if (child == leftChild) {
rChildRect = RRect.fromRectAndCorners(
childRect,
topLeft: const Radius.circular(3.0),
bottomLeft: const Radius.circular(3.0),
);
} else if (child == rightChild) {
rChildRect = RRect.fromRectAndCorners(
childRect,
topRight: const Radius.circular(3.0),
bottomRight: const Radius.circular(3.0),
);
} else {
rChildRect = RRect.fromRectAndCorners(childRect);
}
childParentData.surroundingRect = rChildRect;
start += child.size.width;
child = nextChild(child);
}
}
Size _calculateChildSize(BoxConstraints constraints) {
double maxHeight = _kMinSegmentedControlHeight;
double childWidth = constraints.minWidth / childCount;
RenderBox? child = firstChild;
while (child != null) {
childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity));
child = childAfter(child);
}
childWidth = math.min(childWidth, constraints.maxWidth / childCount);
child = firstChild;
while (child != null) {
final double boxHeight = child.getMaxIntrinsicHeight(childWidth);
maxHeight = math.max(maxHeight, boxHeight);
child = childAfter(child);
}
return Size(childWidth, maxHeight);
}
Size _computeOverallSizeFromChildSize(Size childSize) {
return constraints.constrain(Size(childSize.width * childCount, childSize.height));
}
@override
Size computeDryLayout(BoxConstraints constraints) {
final Size childSize = _calculateChildSize(constraints);
return _computeOverallSizeFromChildSize(childSize);
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
final Size childSize = _calculateChildSize(constraints);
final BoxConstraints childConstraints = BoxConstraints.tightFor(
width: childSize.width,
height: childSize.height,
);
RenderBox? child = firstChild;
while (child != null) {
child.layout(childConstraints, parentUsesSize: true);
child = childAfter(child);
}
switch (textDirection) {
case TextDirection.rtl:
_layoutRects(
childBefore,
lastChild,
firstChild,
);
case TextDirection.ltr:
_layoutRects(
childAfter,
firstChild,
lastChild,
);
}
size = _computeOverallSizeFromChildSize(childSize);
}
@override
void paint(PaintingContext context, Offset offset) {
RenderBox? child = firstChild;
int index = 0;
while (child != null) {
_paintChild(context, offset, child, index);
child = childAfter(child);
index += 1;
}
}
void _paintChild(PaintingContext context, Offset offset, RenderBox child, int childIndex) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
context.canvas.drawRRect(
childParentData.surroundingRect!.shift(offset),
Paint()
..color = backgroundColors[childIndex]
..style = PaintingStyle.fill,
);
context.canvas.drawRRect(
childParentData.surroundingRect!.shift(offset),
Paint()
..color = borderColor
..strokeWidth = 1.0
..style = PaintingStyle.stroke,
);
context.paintChild(child, childParentData.offset + offset);
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
RenderBox? child = lastChild;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
if (childParentData.surroundingRect!.contains(position)) {
return result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
hitTest: (BoxHitTestResult result, Offset localOffset) {
assert(localOffset == position - childParentData.offset);
return child!.hitTest(result, position: localOffset);
},
);
}
child = childParentData.previousSibling;
}
return false;
}
}
| flutter/packages/flutter/lib/src/cupertino/segmented_control.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/segmented_control.dart",
"repo_id": "flutter",
"token_count": 8129
} | 620 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// The location of the Dart Plugin Registrant. This is used by the engine to
/// execute the Dart Plugin Registrant when the Isolate is started or
/// DartPluginRegistrant.ensureInitialized() is called from a background
/// Isolate.
@pragma('vm:entry-point')
const String dartPluginRegistrantLibrary = String.fromEnvironment('flutter.dart_plugin_registrant');
| flutter/packages/flutter/lib/src/dart_plugin_registrant.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/dart_plugin_registrant.dart",
"repo_id": "flutter",
"token_count": 136
} | 621 |
// Copyright 2014 The Flutter 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 '_bitfield_io.dart'
if (dart.library.js_util) '_bitfield_web.dart' as bitfield;
/// The largest SMI value.
///
/// See <https://www.dartlang.org/articles/numeric-computation/#smis-and-mints>
///
/// When compiling to JavaScript, this value is not supported since it is
/// larger than the maximum safe 32bit integer.
const int kMaxUnsignedSMI = bitfield.kMaxUnsignedSMI;
/// A BitField over an enum (or other class whose values implement "index").
/// Only the first 62 values of the enum can be used as indices.
///
/// When compiling to JavaScript, this class is not supported.
abstract class BitField<T extends dynamic> {
/// Creates a bit field of all zeros.
///
/// The given length must be at most 62.
factory BitField(int length) = bitfield.BitField<T>;
/// Creates a bit field filled with a particular value.
///
/// If the value argument is true, the bits are filled with ones. Otherwise,
/// the bits are filled with zeros.
///
/// The given length must be at most 62.
factory BitField.filled(int length, bool value) = bitfield.BitField<T>.filled;
/// Returns whether the bit with the given index is set to one.
bool operator [](T index);
/// Sets the bit with the given index to the given value.
///
/// If value is true, the bit with the given index is set to one. Otherwise,
/// the bit is set to zero.
void operator []=(T index, bool value);
/// Sets all the bits to the given value.
///
/// If the value is true, the bits are all set to one. Otherwise, the bits are
/// all set to zero. Defaults to setting all the bits to zero.
void reset([ bool value = false ]);
}
| flutter/packages/flutter/lib/src/foundation/bitfield.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/bitfield.dart",
"repo_id": "flutter",
"token_count": 521
} | 622 |
// Copyright 2014 The Flutter 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 '_platform_io.dart'
if (dart.library.js_util) '_platform_web.dart' as platform;
import 'assertions.dart';
import 'constants.dart';
/// The [TargetPlatform] that matches the platform on which the framework is
/// currently executing.
///
/// This is the default value of [ThemeData.platform] (hence the name). Widgets
/// from the material library should use [Theme.of] to determine the current
/// platform for styling purposes, rather than using [defaultTargetPlatform].
/// Widgets and render objects at lower layers that try to emulate the
/// underlying platform can depend on [defaultTargetPlatform] directly. The
/// [dart:io.Platform] object should only be used directly when it's critical to
/// actually know the current platform, without any overrides possible (for
/// example, when a system API is about to be called).
///
/// In a test environment, the platform returned is [TargetPlatform.android]
/// regardless of the host platform. (Android was chosen because the tests were
/// originally written assuming Android-like behavior, and we added platform
/// adaptations for iOS later). Tests can check iOS behavior by using the
/// platform override APIs (such as [ThemeData.platform] in the material
/// library) or by setting [debugDefaultTargetPlatformOverride] in debug builds.
///
/// Tests can also create specific platform tests by and adding a `variant:`
/// argument to the test and using a [TargetPlatformVariant].
///
/// See also:
///
/// * [kIsWeb], a boolean which is true if the application is running on the
/// web, where [defaultTargetPlatform] returns which platform the browser is
/// running on.
//
// When adding support for a new platform (e.g. Windows Phone, Raspberry Pi),
// first create a new value on the [TargetPlatform] enum, then add a rule for
// selecting that platform in `_platform_io.dart` and `_platform_web.dart`.
//
// It would be incorrect to make a platform that isn't supported by
// [TargetPlatform] default to the behavior of another platform, because doing
// that would mean we'd be stuck with that platform forever emulating the other,
// and we'd never be able to introduce dedicated behavior for that platform
// (since doing so would be a big breaking change).
@pragma('vm:platform-const-if', !kDebugMode)
TargetPlatform get defaultTargetPlatform => platform.defaultTargetPlatform;
/// The platform that user interaction should adapt to target.
///
/// The [defaultTargetPlatform] getter returns the current platform.
///
/// When using the "flutter run" command, the "o" key will toggle between
/// values of this enum when updating [debugDefaultTargetPlatformOverride].
/// This lets one test how the application will work on various platforms
/// without having to switch emulators or physical devices.
//
// When you add values here, make sure to also add them to
// nextPlatform() in flutter_tools/lib/src/resident_runner.dart so that
// the tool can support the new platform for its "o" option.
enum TargetPlatform {
/// Android: <https://www.android.com/>
android,
/// Fuchsia: <https://fuchsia.dev/fuchsia-src/concepts>
fuchsia,
/// iOS: <https://www.apple.com/ios/>
iOS,
/// Linux: <https://www.linux.org>
linux,
/// macOS: <https://www.apple.com/macos>
macOS,
/// Windows: <https://www.windows.com>
windows,
}
/// Override the [defaultTargetPlatform] in debug builds.
///
/// Setting this to null returns the [defaultTargetPlatform] to its original
/// value (based on the actual current platform).
///
/// Generally speaking this override is only useful for tests. To change the
/// platform that widgets resemble, consider using the platform override APIs
/// (such as [ThemeData.platform] in the material library) instead.
///
/// Setting [debugDefaultTargetPlatformOverride] (as opposed to, say,
/// [ThemeData.platform]) will cause unexpected and undesirable effects. For
/// example, setting this to [TargetPlatform.iOS] when the application is
/// running on Android will cause the TalkBack accessibility tool on Android to
/// be confused because it would be receiving data intended for iOS VoiceOver.
/// Similarly, setting it to [TargetPlatform.android] while on iOS will cause
/// certainly widgets to work assuming the presence of a system-wide back
/// button, which will make those widgets unusable since iOS has no such button.
///
/// Attempting to override this property in non-debug builds causes an error.
TargetPlatform? get debugDefaultTargetPlatformOverride =>
_debugDefaultTargetPlatformOverride;
set debugDefaultTargetPlatformOverride(TargetPlatform? value) {
if (!kDebugMode) {
throw FlutterError(
'Cannot modify debugDefaultTargetPlatformOverride in non-debug builds.');
}
_debugDefaultTargetPlatformOverride = value;
}
TargetPlatform? _debugDefaultTargetPlatformOverride;
| flutter/packages/flutter/lib/src/foundation/platform.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/platform.dart",
"repo_id": "flutter",
"token_count": 1253
} | 623 |
// Copyright 2014 The Flutter 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:ui' show Offset, PointerDeviceKind;
import 'package:flutter/foundation.dart';
import 'package:vector_math/vector_math_64.dart';
import 'constants.dart';
import 'gesture_settings.dart';
export 'dart:ui' show Offset, PointerDeviceKind;
export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder;
export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'gesture_settings.dart' show DeviceGestureSettings;
/// The bit of [PointerEvent.buttons] that corresponds to a cross-device
/// behavior of "primary operation".
///
/// More specifically, it includes:
///
/// * [kTouchContact]: The pointer contacts the touch screen.
/// * [kStylusContact]: The stylus contacts the screen.
/// * [kPrimaryMouseButton]: The primary mouse button.
///
/// See also:
///
/// * [kSecondaryButton], which describes a cross-device behavior of
/// "secondary operation".
/// * [kTertiaryButton], which describes a cross-device behavior of
/// "tertiary operation".
const int kPrimaryButton = 0x01;
/// The bit of [PointerEvent.buttons] that corresponds to a cross-device
/// behavior of "secondary operation".
///
/// It is equivalent to:
///
/// * [kPrimaryStylusButton]: The stylus' primary button.
/// * [kSecondaryMouseButton]: The secondary mouse button.
///
/// See also:
///
/// * [kPrimaryButton], which describes a cross-device behavior of
/// "primary operation".
/// * [kTertiaryButton], which describes a cross-device behavior of
/// "tertiary operation".
const int kSecondaryButton = 0x02;
/// The bit of [PointerEvent.buttons] that corresponds to the primary mouse button.
///
/// The primary mouse button is typically the left button on the top of the
/// mouse but can be reconfigured to be a different physical button.
///
/// See also:
///
/// * [kPrimaryButton], which has the same value but describes its cross-device
/// concept.
const int kPrimaryMouseButton = kPrimaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to the secondary mouse button.
///
/// The secondary mouse button is typically the right button on the top of the
/// mouse but can be reconfigured to be a different physical button.
///
/// See also:
///
/// * [kSecondaryButton], which has the same value but describes its cross-device
/// concept.
const int kSecondaryMouseButton = kSecondaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to when a stylus
/// contacting the screen.
///
/// See also:
///
/// * [kPrimaryButton], which has the same value but describes its cross-device
/// concept.
const int kStylusContact = kPrimaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to the primary stylus button.
///
/// The primary stylus button is typically the top of the stylus and near the
/// tip but can be reconfigured to be a different physical button.
///
/// See also:
///
/// * [kSecondaryButton], which has the same value but describes its cross-device
/// concept.
const int kPrimaryStylusButton = kSecondaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to a cross-device
/// behavior of "tertiary operation".
///
/// It is equivalent to:
///
/// * [kMiddleMouseButton]: The tertiary mouse button.
/// * [kSecondaryStylusButton]: The secondary button on a stylus. This is considered
/// a tertiary button as the primary button of a stylus already corresponds to a
/// "secondary operation" (where stylus contact is the primary operation).
///
/// See also:
///
/// * [kPrimaryButton], which describes a cross-device behavior of
/// "primary operation".
/// * [kSecondaryButton], which describes a cross-device behavior of
/// "secondary operation".
const int kTertiaryButton = 0x04;
/// The bit of [PointerEvent.buttons] that corresponds to the middle mouse button.
///
/// The middle mouse button is typically between the left and right buttons on
/// the top of the mouse but can be reconfigured to be a different physical
/// button.
///
/// See also:
///
/// * [kTertiaryButton], which has the same value but describes its cross-device
/// concept.
const int kMiddleMouseButton = kTertiaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to the secondary stylus button.
///
/// The secondary stylus button is typically on the end of the stylus farthest
/// from the tip but can be reconfigured to be a different physical button.
///
/// See also:
///
/// * [kTertiaryButton], which has the same value but describes its cross-device
/// concept.
const int kSecondaryStylusButton = kTertiaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to the back mouse button.
///
/// The back mouse button is typically on the left side of the mouse but can be
/// reconfigured to be a different physical button.
const int kBackMouseButton = 0x08;
/// The bit of [PointerEvent.buttons] that corresponds to the forward mouse button.
///
/// The forward mouse button is typically on the right side of the mouse but can
/// be reconfigured to be a different physical button.
const int kForwardMouseButton = 0x10;
/// The bit of [PointerEvent.buttons] that corresponds to the pointer contacting
/// a touch screen.
///
/// See also:
///
/// * [kPrimaryButton], which has the same value but describes its cross-device
/// concept.
const int kTouchContact = kPrimaryButton;
/// The bit of [PointerEvent.buttons] that corresponds to the nth mouse button.
///
/// The `number` argument can be at most 62 in Flutter for mobile and desktop,
/// and at most 32 on Flutter for web.
///
/// See [kPrimaryMouseButton], [kSecondaryMouseButton], [kMiddleMouseButton],
/// [kBackMouseButton], and [kForwardMouseButton] for semantic names for some
/// mouse buttons.
int nthMouseButton(int number) => (kPrimaryMouseButton << (number - 1)) & kMaxUnsignedSMI;
/// The bit of [PointerEvent.buttons] that corresponds to the nth stylus button.
///
/// The `number` argument can be at most 62 in Flutter for mobile and desktop,
/// and at most 32 on Flutter for web.
///
/// See [kPrimaryStylusButton] and [kSecondaryStylusButton] for semantic names
/// for some stylus buttons.
int nthStylusButton(int number) => (kPrimaryStylusButton << (number - 1)) & kMaxUnsignedSMI;
/// Returns the button of `buttons` with the smallest integer.
///
/// The `buttons` parameter is a bit field where each set bit represents a button.
/// This function returns the set bit closest to the least significant bit.
///
/// It returns zero when `buttons` is zero.
///
/// Example:
///
/// ```dart
/// assert(smallestButton(0x01) == 0x01);
/// assert(smallestButton(0x11) == 0x01);
/// assert(smallestButton(0x10) == 0x10);
/// assert(smallestButton(0) == 0);
/// ```
///
/// See also:
///
/// * [isSingleButton], which checks if a `buttons` contains exactly one button.
int smallestButton(int buttons) => buttons & (-buttons);
/// Returns whether `buttons` contains one and only one button.
///
/// The `buttons` parameter is a bit field where each set bit represents a button.
/// This function returns whether there is only one set bit in the given integer.
///
/// It returns false when `buttons` is zero.
///
/// Example:
///
/// ```dart
/// assert(isSingleButton(0x1));
/// assert(!isSingleButton(0x11));
/// assert(!isSingleButton(0));
/// ```
///
/// See also:
///
/// * [smallestButton], which returns the button in a `buttons` bit field with
/// the smallest integer button.
bool isSingleButton(int buttons) => buttons != 0 && (smallestButton(buttons) == buttons);
/// Base class for touch, stylus, or mouse events.
///
/// Pointer events operate in the coordinate space of the screen, scaled to
/// logical pixels. Logical pixels approximate a grid with about 38 pixels per
/// centimeter, or 96 pixels per inch.
///
/// This allows gestures to be recognized independent of the precise hardware
/// characteristics of the device. In particular, features such as touch slop
/// (see [kTouchSlop]) can be defined in terms of roughly physical lengths so
/// that the user can shift their finger by the same distance on a high-density
/// display as on a low-resolution device.
///
/// For similar reasons, pointer events are not affected by any transforms in
/// the rendering layer. This means that deltas may need to be scaled before
/// being applied to movement within the rendering. For example, if a scrolling
/// list is shown scaled by 2x, the pointer deltas will have to be scaled by the
/// inverse amount if the list is to appear to scroll with the user's finger.
///
/// See also:
///
/// * [dart:ui.FlutterView.devicePixelRatio], which defines the device's
/// current resolution.
/// * [Listener], a widget that calls callbacks in response to common pointer
/// events.
@immutable
abstract class PointerEvent with Diagnosticable {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const PointerEvent({
this.viewId = 0,
this.embedderId = 0,
this.timeStamp = Duration.zero,
this.pointer = 0,
this.kind = PointerDeviceKind.touch,
this.device = 0,
this.position = Offset.zero,
this.delta = Offset.zero,
this.buttons = 0,
this.down = false,
this.obscured = false,
this.pressure = 1.0,
this.pressureMin = 1.0,
this.pressureMax = 1.0,
this.distance = 0.0,
this.distanceMax = 0.0,
this.size = 0.0,
this.radiusMajor = 0.0,
this.radiusMinor = 0.0,
this.radiusMin = 0.0,
this.radiusMax = 0.0,
this.orientation = 0.0,
this.tilt = 0.0,
this.platformData = 0,
this.synthesized = false,
this.transform,
this.original,
});
/// The ID of the [FlutterView] which this event originated from.
final int viewId;
/// Unique identifier that ties the [PointerEvent] to the embedder event that created it.
///
/// No two pointer events can have the same [embedderId] on platforms that set it.
/// This is different from [pointer] identifier - used for hit-testing,
/// whereas [embedderId] is used to identify the platform event.
///
/// On Android this is ID of the underlying [MotionEvent](https://developer.android.com/reference/android/view/MotionEvent).
final int embedderId;
/// Time of event dispatch, relative to an arbitrary timeline.
final Duration timeStamp;
/// Unique identifier for the pointer, not reused. Changes for each new
/// pointer down event.
final int pointer;
/// The kind of input device for which the event was generated.
final PointerDeviceKind kind;
/// Unique identifier for the pointing device, reused across interactions.
final int device;
/// Coordinate of the position of the pointer, in logical pixels in the global
/// coordinate space.
///
/// See also:
///
/// * [localPosition], which is the [position] transformed into the local
/// coordinate system of the event receiver.
final Offset position;
/// The [position] transformed into the event receiver's local coordinate
/// system according to [transform].
///
/// If this event has not been transformed, [position] is returned as-is.
/// See also:
///
/// * [position], which is the position in the global coordinate system of
/// the screen.
Offset get localPosition => position;
/// Distance in logical pixels that the pointer moved since the last
/// [PointerMoveEvent] or [PointerHoverEvent].
///
/// This value is always 0.0 for down, up, and cancel events.
///
/// See also:
///
/// * [localDelta], which is the [delta] transformed into the local
/// coordinate space of the event receiver.
final Offset delta;
/// The [delta] transformed into the event receiver's local coordinate
/// system according to [transform].
///
/// If this event has not been transformed, [delta] is returned as-is.
///
/// See also:
///
/// * [delta], which is the distance the pointer moved in the global
/// coordinate system of the screen.
Offset get localDelta => delta;
/// Bit field using the *Button constants such as [kPrimaryMouseButton],
/// [kSecondaryStylusButton], etc.
///
/// For example, if this has the value 6 and the
/// [kind] is [PointerDeviceKind.invertedStylus], then this indicates an
/// upside-down stylus with both its primary and secondary buttons pressed.
final int buttons;
/// Set if the pointer is currently down.
///
/// For touch and stylus pointers, this means the object (finger, pen) is in
/// contact with the input surface. For mice, it means a button is pressed.
final bool down;
/// Set if an application from a different security domain is in any way
/// obscuring this application's window.
///
/// This is not currently implemented.
final bool obscured;
/// The pressure of the touch.
///
/// This value is a number ranging from 0.0, indicating a touch with no
/// discernible pressure, to 1.0, indicating a touch with "normal" pressure,
/// and possibly beyond, indicating a stronger touch. For devices that do not
/// detect pressure (e.g. mice), returns 1.0.
final double pressure;
/// The minimum value that [pressure] can return for this pointer.
///
/// For devices that do not detect pressure (e.g. mice), returns 1.0.
/// This will always be a number less than or equal to 1.0.
final double pressureMin;
/// The maximum value that [pressure] can return for this pointer.
///
/// For devices that do not detect pressure (e.g. mice), returns 1.0.
/// This will always be a greater than or equal to 1.0.
final double pressureMax;
/// The distance of the detected object from the input surface.
///
/// For instance, this value could be the distance of a stylus or finger
/// from a touch screen, in arbitrary units on an arbitrary (not necessarily
/// linear) scale. If the pointer is down, this is 0.0 by definition.
final double distance;
/// The minimum value that [distance] can return for this pointer.
///
/// This value is always 0.0.
double get distanceMin => 0.0;
/// The maximum value that [distance] can return for this pointer.
///
/// If this input device cannot detect "hover touch" input events,
/// then this will be 0.0.
final double distanceMax;
/// The area of the screen being pressed.
///
/// This value is scaled to a range between 0 and 1. It can be used to
/// determine fat touch events. This value is only set on Android and is
/// a device specific approximation within the range of detectable values.
/// So, for example, the value of 0.1 could mean a touch with the tip of
/// the finger, 0.2 a touch with full finger, and 0.3 the full palm.
///
/// Because this value uses device-specific range and is uncalibrated,
/// it is of limited use and is primarily retained in order to be able
/// to reconstruct original pointer events for [AndroidView].
final double size;
/// The radius of the contact ellipse along the major axis, in logical pixels.
final double radiusMajor;
/// The radius of the contact ellipse along the minor axis, in logical pixels.
final double radiusMinor;
/// The minimum value that could be reported for [radiusMajor] and [radiusMinor]
/// for this pointer, in logical pixels.
final double radiusMin;
/// The maximum value that could be reported for [radiusMajor] and [radiusMinor]
/// for this pointer, in logical pixels.
final double radiusMax;
/// The orientation angle of the detected object, in radians.
///
/// For [PointerDeviceKind.touch] events:
///
/// The angle of the contact ellipse, in radians in the range:
///
/// -pi/2 < orientation <= pi/2
///
/// ...giving the angle of the major axis of the ellipse with the y-axis
/// (negative angles indicating an orientation along the top-left /
/// bottom-right diagonal, positive angles indicating an orientation along the
/// top-right / bottom-left diagonal, and zero indicating an orientation
/// parallel with the y-axis).
///
/// For [PointerDeviceKind.stylus] and [PointerDeviceKind.invertedStylus] events:
///
/// The angle of the stylus, in radians in the range:
///
/// -pi < orientation <= pi
///
/// ...giving the angle of the axis of the stylus projected onto the input
/// surface, relative to the positive y-axis of that surface (thus 0.0
/// indicates the stylus, if projected onto that surface, would go from the
/// contact point vertically up in the positive y-axis direction, pi would
/// indicate that the stylus would go down in the negative y-axis direction;
/// pi/4 would indicate that the stylus goes up and to the right, -pi/2 would
/// indicate that the stylus goes to the left, etc).
final double orientation;
/// The tilt angle of the detected object, in radians.
///
/// For [PointerDeviceKind.stylus] and [PointerDeviceKind.invertedStylus] events:
///
/// The angle of the stylus, in radians in the range:
///
/// 0 <= tilt <= pi/2
///
/// ...giving the angle of the axis of the stylus, relative to the axis
/// perpendicular to the input surface (thus 0.0 indicates the stylus is
/// orthogonal to the plane of the input surface, while pi/2 indicates that
/// the stylus is flat on that surface).
final double tilt;
/// Opaque platform-specific data associated with the event.
final int platformData;
/// Set if the event was synthesized by Flutter.
///
/// We occasionally synthesize PointerEvents that aren't exact translations
/// of [PointerData] from the engine to cover small cross-OS discrepancies
/// in pointer behaviors.
///
/// For instance, on end events, Android always drops any location changes
/// that happened between its reporting intervals when emitting the end events.
///
/// On iOS, minor incorrect location changes from the previous move events
/// can be reported on end events. We synthesize a [PointerEvent] to cover
/// the difference between the 2 events in that case.
final bool synthesized;
/// The transformation used to transform this event from the global coordinate
/// space into the coordinate space of the event receiver.
///
/// This value affects what is returned by [localPosition] and [localDelta].
/// If this value is null, it is treated as the identity transformation.
///
/// Unlike a paint transform, this transform usually does not contain any
/// "perspective" components, meaning that the third row and the third column
/// of the matrix should be equal to "0, 0, 1, 0". This ensures that
/// [localPosition] describes the point in the local coordinate system of the
/// event receiver at which the user is actually touching the screen.
///
/// See also:
///
/// * [transformed], which transforms this event into a different coordinate
/// space.
final Matrix4? transform;
/// The original un-transformed [PointerEvent] before any [transform]s were
/// applied.
///
/// If [transform] is null or the identity transformation this may be null.
///
/// When multiple event receivers in different coordinate spaces receive an
/// event, they all receive the event transformed to their local coordinate
/// space. The [original] property can be used to determine if all those
/// transformed events actually originated from the same pointer interaction.
final PointerEvent? original;
/// Transforms the event from the global coordinate space into the coordinate
/// space of an event receiver.
///
/// The coordinate space of the event receiver is described by `transform`. A
/// null value for `transform` is treated as the identity transformation.
///
/// The resulting event will store the base event as [original], delegates
/// most properties to [original], except for [localPosition] and [localDelta],
/// which are calculated based on [transform] on first use and cached.
///
/// The method may return the same object instance if for example the
/// transformation has no effect on the event. Otherwise, the resulting event
/// will be a subclass of, but not exactly, the original event class (e.g.
/// [PointerDownEvent.transformed] may return a subclass of [PointerDownEvent]).
///
/// Transforms are not commutative, and are based on [original] events.
/// If this method is called on a transformed event, the provided `transform`
/// will override (instead of multiplied onto) the existing [transform] and
/// used to calculate the new [localPosition] and [localDelta].
PointerEvent transformed(Matrix4? transform);
/// Creates a copy of event with the specified properties replaced.
///
/// Calling this method on a transformed event will return a new transformed
/// event based on the current [transform] and the provided properties.
PointerEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
});
/// Returns the transformation of `position` into the coordinate system
/// described by `transform`.
///
/// The z-value of `position` is assumed to be 0.0. If `transform` is null,
/// `position` is returned as-is.
static Offset transformPosition(Matrix4? transform, Offset position) {
if (transform == null) {
return position;
}
final Vector3 position3 = Vector3(position.dx, position.dy, 0.0);
final Vector3 transformed3 = transform.perspectiveTransform(position3);
return Offset(transformed3.x, transformed3.y);
}
/// Transforms `untransformedDelta` into the coordinate system described by
/// `transform`.
///
/// It uses the provided `untransformedEndPosition` and
/// `transformedEndPosition` of the provided delta to increase accuracy.
///
/// If `transform` is null, `untransformedDelta` is returned.
static Offset transformDeltaViaPositions({
required Offset untransformedEndPosition,
Offset? transformedEndPosition,
required Offset untransformedDelta,
required Matrix4? transform,
}) {
if (transform == null) {
return untransformedDelta;
}
// We could transform the delta directly with the transformation matrix.
// While that is mathematically equivalent, in practice we are seeing a
// greater precision error with that approach. Instead, we are transforming
// start and end point of the delta separately and calculate the delta in
// the new space for greater accuracy.
transformedEndPosition ??= transformPosition(transform, untransformedEndPosition);
final Offset transformedStartPosition = transformPosition(transform, untransformedEndPosition - untransformedDelta);
return transformedEndPosition - transformedStartPosition;
}
/// Removes the "perspective" component from `transform`.
///
/// When applying the resulting transform matrix to a point with a
/// z-coordinate of zero (which is generally assumed for all points
/// represented by an [Offset]), the other coordinates will get transformed as
/// before, but the new z-coordinate is going to be zero again. This is
/// achieved by setting the third column and third row of the matrix to
/// "0, 0, 1, 0".
static Matrix4 removePerspectiveTransform(Matrix4 transform) {
final Vector4 vector = Vector4(0, 0, 1, 0);
return transform.clone()
..setColumn(2, vector)
..setRow(2, vector);
}
}
// A mixin that adds implementation for [debugFillProperties] and [toStringFull]
// to [PointerEvent].
mixin _PointerEventDescription on PointerEvent {
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('position', position));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition, defaultValue: position, level: DiagnosticLevel.debug));
properties.add(DiagnosticsProperty<Offset>('delta', delta, defaultValue: Offset.zero, level: DiagnosticLevel.debug));
properties.add(DiagnosticsProperty<Offset>('localDelta', localDelta, defaultValue: delta, level: DiagnosticLevel.debug));
properties.add(DiagnosticsProperty<Duration>('timeStamp', timeStamp, defaultValue: Duration.zero, level: DiagnosticLevel.debug));
properties.add(IntProperty('pointer', pointer, level: DiagnosticLevel.debug));
properties.add(EnumProperty<PointerDeviceKind>('kind', kind, level: DiagnosticLevel.debug));
properties.add(IntProperty('device', device, defaultValue: 0, level: DiagnosticLevel.debug));
properties.add(IntProperty('buttons', buttons, defaultValue: 0, level: DiagnosticLevel.debug));
properties.add(DiagnosticsProperty<bool>('down', down, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('pressure', pressure, defaultValue: 1.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('pressureMin', pressureMin, defaultValue: 1.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('pressureMax', pressureMax, defaultValue: 1.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('distance', distance, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('distanceMin', distanceMin, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('distanceMax', distanceMax, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('size', size, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('radiusMajor', radiusMajor, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('radiusMinor', radiusMinor, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('radiusMin', radiusMin, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('radiusMax', radiusMax, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('orientation', orientation, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(DoubleProperty('tilt', tilt, defaultValue: 0.0, level: DiagnosticLevel.debug));
properties.add(IntProperty('platformData', platformData, defaultValue: 0, level: DiagnosticLevel.debug));
properties.add(FlagProperty('obscured', value: obscured, ifTrue: 'obscured', level: DiagnosticLevel.debug));
properties.add(FlagProperty('synthesized', value: synthesized, ifTrue: 'synthesized', level: DiagnosticLevel.debug));
properties.add(IntProperty('embedderId', embedderId, defaultValue: 0, level: DiagnosticLevel.debug));
properties.add(IntProperty('viewId', viewId, defaultValue: 0, level: DiagnosticLevel.debug));
}
/// Returns a complete textual description of this event.
String toStringFull() {
return toString(minLevel: DiagnosticLevel.fine);
}
}
abstract class _AbstractPointerEvent implements PointerEvent { }
// The base class for transformed pointer event classes.
//
// A _TransformedPointerEvent stores an [original] event and the [transform]
// matrix. It defers all field getters to the original event, except for
// [localPosition] and [localDelta], which are calculated when first used.
abstract class _TransformedPointerEvent extends _AbstractPointerEvent with Diagnosticable, _PointerEventDescription {
@override
PointerEvent get original;
@override
Matrix4 get transform;
@override
int get embedderId => original.embedderId;
@override
Duration get timeStamp => original.timeStamp;
@override
int get pointer => original.pointer;
@override
PointerDeviceKind get kind => original.kind;
@override
int get device => original.device;
@override
Offset get position => original.position;
@override
Offset get delta => original.delta;
@override
int get buttons => original.buttons;
@override
bool get down => original.down;
@override
bool get obscured => original.obscured;
@override
double get pressure => original.pressure;
@override
double get pressureMin => original.pressureMin;
@override
double get pressureMax => original.pressureMax;
@override
double get distance => original.distance;
@override
double get distanceMin => 0.0;
@override
double get distanceMax => original.distanceMax;
@override
double get size => original.size;
@override
double get radiusMajor => original.radiusMajor;
@override
double get radiusMinor => original.radiusMinor;
@override
double get radiusMin => original.radiusMin;
@override
double get radiusMax => original.radiusMax;
@override
double get orientation => original.orientation;
@override
double get tilt => original.tilt;
@override
int get platformData => original.platformData;
@override
bool get synthesized => original.synthesized;
@override
late final Offset localPosition = PointerEvent.transformPosition(transform, position);
@override
late final Offset localDelta = PointerEvent.transformDeltaViaPositions(
transform: transform,
untransformedDelta: delta,
untransformedEndPosition: position,
transformedEndPosition: localPosition,
);
@override
int get viewId => original.viewId;
}
mixin _CopyPointerAddedEvent on PointerEvent {
@override
PointerAddedEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerAddedEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
obscured: obscured ?? this.obscured,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distance: distance ?? this.distance,
distanceMax: distanceMax ?? this.distanceMax,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The device has started tracking the pointer.
///
/// For example, the pointer might be hovering above the device, having not yet
/// made contact with the surface of the device.
class PointerAddedEvent extends PointerEvent with _PointerEventDescription, _CopyPointerAddedEvent {
/// Creates a pointer added event.
const PointerAddedEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.obscured,
super.pressureMin,
super.pressureMax,
super.distance,
super.distanceMax,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.embedderId,
}) : super(
pressure: 0.0,
);
@override
PointerAddedEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerAddedEvent(original as PointerAddedEvent? ?? this, transform);
}
}
class _TransformedPointerAddedEvent extends _TransformedPointerEvent with _CopyPointerAddedEvent implements PointerAddedEvent {
_TransformedPointerAddedEvent(this.original, this.transform);
@override
final PointerAddedEvent original;
@override
final Matrix4 transform;
@override
PointerAddedEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerRemovedEvent on PointerEvent {
@override
PointerRemovedEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerRemovedEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
obscured: obscured ?? this.obscured,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distanceMax: distanceMax ?? this.distanceMax,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The device is no longer tracking the pointer.
///
/// For example, the pointer might have drifted out of the device's hover
/// detection range or might have been disconnected from the system entirely.
class PointerRemovedEvent extends PointerEvent with _PointerEventDescription, _CopyPointerRemovedEvent {
/// Creates a pointer removed event.
const PointerRemovedEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.obscured,
super.pressureMin,
super.pressureMax,
super.distanceMax,
super.radiusMin,
super.radiusMax,
PointerRemovedEvent? super.original,
super.embedderId,
}) : super(
pressure: 0.0,
);
@override
PointerRemovedEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerRemovedEvent(original as PointerRemovedEvent? ?? this, transform);
}
}
class _TransformedPointerRemovedEvent extends _TransformedPointerEvent with _CopyPointerRemovedEvent implements PointerRemovedEvent {
_TransformedPointerRemovedEvent(this.original, this.transform);
@override
final PointerRemovedEvent original;
@override
final Matrix4 transform;
@override
PointerRemovedEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerHoverEvent on PointerEvent {
@override
PointerHoverEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerHoverEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
delta: delta ?? this.delta,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distance: distance ?? this.distance,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
synthesized: synthesized ?? this.synthesized,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer has moved with respect to the device while the pointer is not
/// in contact with the device.
///
/// See also:
///
/// * [PointerEnterEvent], which reports when the pointer has entered an
/// object.
/// * [PointerExitEvent], which reports when the pointer has left an object.
/// * [PointerMoveEvent], which reports movement while the pointer is in
/// contact with the device.
/// * [Listener.onPointerHover], which allows callers to be notified of these
/// events in a widget tree.
class PointerHoverEvent extends PointerEvent with _PointerEventDescription, _CopyPointerHoverEvent {
/// Creates a pointer hover event.
const PointerHoverEvent({
super.viewId,
super.timeStamp,
super.kind,
super.pointer,
super.device,
super.position,
super.delta,
super.buttons,
super.obscured,
super.pressureMin,
super.pressureMax,
super.distance,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.synthesized,
super.embedderId,
}) : super(
down: false,
pressure: 0.0,
);
@override
PointerHoverEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerHoverEvent(original as PointerHoverEvent? ?? this, transform);
}
}
class _TransformedPointerHoverEvent extends _TransformedPointerEvent with _CopyPointerHoverEvent implements PointerHoverEvent {
_TransformedPointerHoverEvent(this.original, this.transform);
@override
final PointerHoverEvent original;
@override
final Matrix4 transform;
@override
PointerHoverEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerEnterEvent on PointerEvent {
@override
PointerEnterEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerEnterEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
delta: delta ?? this.delta,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distance: distance ?? this.distance,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
synthesized: synthesized ?? this.synthesized,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer has moved with respect to the device while the pointer is or is
/// not in contact with the device, and it has entered a target object.
///
/// See also:
///
/// * [PointerHoverEvent], which reports when the pointer has moved while
/// within an object.
/// * [PointerExitEvent], which reports when the pointer has left an object.
/// * [PointerMoveEvent], which reports movement while the pointer is in
/// contact with the device.
/// * [MouseRegion.onEnter], which allows callers to be notified of these
/// events in a widget tree.
class PointerEnterEvent extends PointerEvent with _PointerEventDescription, _CopyPointerEnterEvent {
/// Creates a pointer enter event.
const PointerEnterEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.delta,
super.buttons,
super.obscured,
super.pressureMin,
super.pressureMax,
super.distance,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.down,
super.synthesized,
super.embedderId,
}) : // Dart doesn't support comparing enums with == in const contexts yet.
// https://github.com/dart-lang/language/issues/1811
assert(!identical(kind, PointerDeviceKind.trackpad)),
super(
pressure: 0.0,
);
/// Creates an enter event from a [PointerEvent].
///
/// This is used by the [MouseTracker] to synthesize enter events.
factory PointerEnterEvent.fromMouseEvent(PointerEvent event) => PointerEnterEvent(
viewId: event.viewId,
timeStamp: event.timeStamp,
pointer: event.pointer,
kind: event.kind,
device: event.device,
position: event.position,
delta: event.delta,
buttons: event.buttons,
obscured: event.obscured,
pressureMin: event.pressureMin,
pressureMax: event.pressureMax,
distance: event.distance,
distanceMax: event.distanceMax,
size: event.size,
radiusMajor: event.radiusMajor,
radiusMinor: event.radiusMinor,
radiusMin: event.radiusMin,
radiusMax: event.radiusMax,
orientation: event.orientation,
tilt: event.tilt,
down: event.down,
synthesized: event.synthesized,
).transformed(event.transform);
@override
PointerEnterEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerEnterEvent(original as PointerEnterEvent? ?? this, transform);
}
}
class _TransformedPointerEnterEvent extends _TransformedPointerEvent with _CopyPointerEnterEvent implements PointerEnterEvent {
_TransformedPointerEnterEvent(this.original, this.transform);
@override
final PointerEnterEvent original;
@override
final Matrix4 transform;
@override
PointerEnterEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerExitEvent on PointerEvent {
@override
PointerExitEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerExitEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
delta: delta ?? this.delta,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distance: distance ?? this.distance,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
synthesized: synthesized ?? this.synthesized,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer has moved with respect to the device while the pointer is or is
/// not in contact with the device, and exited a target object.
///
/// See also:
///
/// * [PointerHoverEvent], which reports when the pointer has moved while
/// within an object.
/// * [PointerEnterEvent], which reports when the pointer has entered an object.
/// * [PointerMoveEvent], which reports movement while the pointer is in
/// contact with the device.
/// * [MouseRegion.onExit], which allows callers to be notified of these
/// events in a widget tree.
class PointerExitEvent extends PointerEvent with _PointerEventDescription, _CopyPointerExitEvent {
/// Creates a pointer exit event.
const PointerExitEvent({
super.viewId,
super.timeStamp,
super.kind,
super.pointer,
super.device,
super.position,
super.delta,
super.buttons,
super.obscured,
super.pressureMin,
super.pressureMax,
super.distance,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.down,
super.synthesized,
super.embedderId,
}) : assert(!identical(kind, PointerDeviceKind.trackpad)),
super(
pressure: 0.0,
);
/// Creates an exit event from a [PointerEvent].
///
/// This is used by the [MouseTracker] to synthesize exit events.
factory PointerExitEvent.fromMouseEvent(PointerEvent event) => PointerExitEvent(
viewId: event.viewId,
timeStamp: event.timeStamp,
pointer: event.pointer,
kind: event.kind,
device: event.device,
position: event.position,
delta: event.delta,
buttons: event.buttons,
obscured: event.obscured,
pressureMin: event.pressureMin,
pressureMax: event.pressureMax,
distance: event.distance,
distanceMax: event.distanceMax,
size: event.size,
radiusMajor: event.radiusMajor,
radiusMinor: event.radiusMinor,
radiusMin: event.radiusMin,
radiusMax: event.radiusMax,
orientation: event.orientation,
tilt: event.tilt,
down: event.down,
synthesized: event.synthesized,
).transformed(event.transform);
@override
PointerExitEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerExitEvent(original as PointerExitEvent? ?? this, transform);
}
}
class _TransformedPointerExitEvent extends _TransformedPointerEvent with _CopyPointerExitEvent implements PointerExitEvent {
_TransformedPointerExitEvent(this.original, this.transform);
@override
final PointerExitEvent original;
@override
final Matrix4 transform;
@override
PointerExitEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerDownEvent on PointerEvent {
@override
PointerDownEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerDownEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
pointer: pointer ?? this.pointer,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressure: pressure ?? this.pressure,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer has made contact with the device.
///
/// See also:
///
/// * [Listener.onPointerDown], which allows callers to be notified of these
/// events in a widget tree.
class PointerDownEvent extends PointerEvent with _PointerEventDescription, _CopyPointerDownEvent {
/// Creates a pointer down event.
const PointerDownEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.buttons = kPrimaryButton,
super.obscured,
super.pressure,
super.pressureMin,
super.pressureMax,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.embedderId,
}) : assert(!identical(kind, PointerDeviceKind.trackpad)),
super(
down: true,
distance: 0.0,
);
@override
PointerDownEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerDownEvent(original as PointerDownEvent? ?? this, transform);
}
}
class _TransformedPointerDownEvent extends _TransformedPointerEvent with _CopyPointerDownEvent implements PointerDownEvent {
_TransformedPointerDownEvent(this.original, this.transform);
@override
final PointerDownEvent original;
@override
final Matrix4 transform;
@override
PointerDownEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerMoveEvent on PointerEvent {
@override
PointerMoveEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerMoveEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
pointer: pointer ?? this.pointer,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
delta: delta ?? this.delta,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressure: pressure ?? this.pressure,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
synthesized: synthesized ?? this.synthesized,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer has moved with respect to the device while the pointer is in
/// contact with the device.
///
/// See also:
///
/// * [PointerHoverEvent], which reports movement while the pointer is not in
/// contact with the device.
/// * [Listener.onPointerMove], which allows callers to be notified of these
/// events in a widget tree.
class PointerMoveEvent extends PointerEvent with _PointerEventDescription, _CopyPointerMoveEvent {
/// Creates a pointer move event.
const PointerMoveEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.delta,
super.buttons = kPrimaryButton,
super.obscured,
super.pressure,
super.pressureMin,
super.pressureMax,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.platformData,
super.synthesized,
super.embedderId,
}) : assert(!identical(kind, PointerDeviceKind.trackpad)),
super(
down: true,
distance: 0.0,
);
@override
PointerMoveEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerMoveEvent(original as PointerMoveEvent? ?? this, transform);
}
}
class _TransformedPointerMoveEvent extends _TransformedPointerEvent with _CopyPointerMoveEvent implements PointerMoveEvent {
_TransformedPointerMoveEvent(this.original, this.transform);
@override
final PointerMoveEvent original;
@override
final Matrix4 transform;
@override
PointerMoveEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerUpEvent on PointerEvent {
@override
PointerUpEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? localPosition,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerUpEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
pointer: pointer ?? this.pointer,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressure: pressure ?? this.pressure,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distance: distance ?? this.distance,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer has stopped making contact with the device.
///
/// See also:
///
/// * [Listener.onPointerUp], which allows callers to be notified of these
/// events in a widget tree.
class PointerUpEvent extends PointerEvent with _PointerEventDescription, _CopyPointerUpEvent {
/// Creates a pointer up event.
const PointerUpEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.buttons,
super.obscured,
// Allow pressure customization here because PointerUpEvent can contain
// non-zero pressure. See https://github.com/flutter/flutter/issues/31340
super.pressure = 0.0,
super.pressureMin,
super.pressureMax,
super.distance,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.embedderId,
}) : assert(!identical(kind, PointerDeviceKind.trackpad)),
super(
down: false,
);
@override
PointerUpEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerUpEvent(original as PointerUpEvent? ?? this, transform);
}
}
class _TransformedPointerUpEvent extends _TransformedPointerEvent with _CopyPointerUpEvent implements PointerUpEvent {
_TransformedPointerUpEvent(this.original, this.transform);
@override
final PointerUpEvent original;
@override
final Matrix4 transform;
@override
PointerUpEvent transformed(Matrix4? transform) => original.transformed(transform);
}
/// An event that corresponds to a discrete pointer signal.
///
/// Pointer signals are events that originate from the pointer but don't change
/// the state of the pointer itself, and are discrete rather than needing to be
/// interpreted in the context of a series of events.
///
/// See also:
///
/// * [Listener.onPointerSignal], which allows callers to be notified of these
/// events in a widget tree.
/// * [PointerSignalResolver], which provides an opt-in mechanism whereby
/// participating agents may disambiguate an event's target.
abstract class PointerSignalEvent extends PointerEvent {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const PointerSignalEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind = PointerDeviceKind.mouse,
super.device,
super.position,
super.embedderId,
});
}
mixin _CopyPointerScrollEvent on PointerEvent {
/// The amount to scroll, in logical pixels.
Offset get scrollDelta;
@override
PointerScrollEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerScrollEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
scrollDelta: scrollDelta,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer issued a scroll event.
///
/// Scrolling the scroll wheel on a mouse is an example of an event that
/// would create a [PointerScrollEvent].
///
/// See also:
///
/// * [Listener.onPointerSignal], which allows callers to be notified of these
/// events in a widget tree.
/// * [PointerSignalResolver], which provides an opt-in mechanism whereby
/// participating agents may disambiguate an event's target.
class PointerScrollEvent extends PointerSignalEvent with _PointerEventDescription, _CopyPointerScrollEvent {
/// Creates a pointer scroll event.
const PointerScrollEvent({
super.viewId,
super.timeStamp,
super.kind,
super.device,
super.position,
this.scrollDelta = Offset.zero,
super.embedderId,
});
@override
final Offset scrollDelta;
@override
PointerScrollEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerScrollEvent(original as PointerScrollEvent? ?? this, transform);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('scrollDelta', scrollDelta));
}
}
class _TransformedPointerScrollEvent extends _TransformedPointerEvent with _CopyPointerScrollEvent implements PointerScrollEvent {
_TransformedPointerScrollEvent(this.original, this.transform);
@override
final PointerScrollEvent original;
@override
final Matrix4 transform;
@override
Offset get scrollDelta => original.scrollDelta;
@override
PointerScrollEvent transformed(Matrix4? transform) => original.transformed(transform);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('scrollDelta', scrollDelta));
}
}
mixin _CopyPointerScrollInertiaCancelEvent on PointerEvent {
@override
PointerScrollInertiaCancelEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerScrollInertiaCancelEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pointer issued a scroll-inertia cancel event.
///
/// Touching the trackpad immediately after a scroll is an example of an event
/// that would create a [PointerScrollInertiaCancelEvent].
///
/// See also:
///
/// * [Listener.onPointerSignal], which allows callers to be notified of these
/// events in a widget tree.
/// * [PointerSignalResolver], which provides an opt-in mechanism whereby
/// participating agents may disambiguate an event's target.
class PointerScrollInertiaCancelEvent extends PointerSignalEvent with _PointerEventDescription, _CopyPointerScrollInertiaCancelEvent {
/// Creates a pointer scroll-inertia cancel event.
const PointerScrollInertiaCancelEvent({
super.viewId,
super.timeStamp,
super.kind,
super.device,
super.position,
super.embedderId,
});
@override
PointerScrollInertiaCancelEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerScrollInertiaCancelEvent(original as PointerScrollInertiaCancelEvent? ?? this, transform);
}
}
class _TransformedPointerScrollInertiaCancelEvent extends _TransformedPointerEvent with _CopyPointerScrollInertiaCancelEvent implements PointerScrollInertiaCancelEvent {
_TransformedPointerScrollInertiaCancelEvent(this.original, this.transform);
@override
final PointerScrollInertiaCancelEvent original;
@override
final Matrix4 transform;
@override
PointerScrollInertiaCancelEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerScaleEvent on PointerEvent {
/// The scale (zoom factor) of the event.
double get scale;
@override
PointerScaleEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
double? scale,
}) {
return PointerScaleEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
embedderId: embedderId ?? this.embedderId,
scale: scale ?? this.scale,
).transformed(transform);
}
}
/// The pointer issued a scale event.
///
/// Pinching-to-zoom in the browser is an example of an event
/// that would create a [PointerScaleEvent].
///
/// See also:
///
/// * [Listener.onPointerSignal], which allows callers to be notified of these
/// events in a widget tree.
/// * [PointerSignalResolver], which provides an opt-in mechanism whereby
/// participating agents may disambiguate an event's target.
class PointerScaleEvent extends PointerSignalEvent with _PointerEventDescription, _CopyPointerScaleEvent {
/// Creates a pointer scale event.
const PointerScaleEvent({
super.viewId,
super.timeStamp,
super.kind,
super.device,
super.position,
super.embedderId,
this.scale = 1.0,
});
@override
final double scale;
@override
PointerScaleEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerScaleEvent(original as PointerScaleEvent? ?? this, transform);
}
}
class _TransformedPointerScaleEvent extends _TransformedPointerEvent with _CopyPointerScaleEvent implements PointerScaleEvent {
_TransformedPointerScaleEvent(this.original, this.transform);
@override
final PointerScaleEvent original;
@override
final Matrix4 transform;
@override
double get scale => original.scale;
@override
PointerScaleEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerPanZoomStartEvent on PointerEvent {
@override
PointerPanZoomStartEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
assert(kind == null || identical(kind, PointerDeviceKind.trackpad));
return PointerPanZoomStartEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
device: device ?? this.device,
position: position ?? this.position,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// A pan/zoom has begun on this pointer.
///
/// See also:
///
/// * [Listener.onPointerPanZoomStart], which allows callers to be notified of these
/// events in a widget tree.
class PointerPanZoomStartEvent extends PointerEvent with _PointerEventDescription, _CopyPointerPanZoomStartEvent {
/// Creates a pointer pan/zoom start event.
const PointerPanZoomStartEvent({
super.viewId,
super.timeStamp,
super.device,
super.pointer,
super.position,
super.embedderId,
super.synthesized,
}) : super(kind: PointerDeviceKind.trackpad);
@override
PointerPanZoomStartEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerPanZoomStartEvent(original as PointerPanZoomStartEvent? ?? this, transform);
}
}
class _TransformedPointerPanZoomStartEvent extends _TransformedPointerEvent with _CopyPointerPanZoomStartEvent implements PointerPanZoomStartEvent {
_TransformedPointerPanZoomStartEvent(this.original, this.transform);
@override
final PointerPanZoomStartEvent original;
@override
final Matrix4 transform;
@override
PointerPanZoomStartEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerPanZoomUpdateEvent on PointerEvent {
/// The total pan offset of the pan/zoom.
Offset get pan;
/// The total pan offset of the pan/zoom, transformed into local coordinates.
Offset get localPan;
/// The amount the pan offset changed since the last event.
Offset get panDelta;
/// The amount the pan offset changed since the last event, transformed into local coordinates.
Offset get localPanDelta;
/// The scale (zoom factor) of the pan/zoom.
double get scale;
/// The amount the pan/zoom has rotated in radians so far.
double get rotation;
@override
PointerPanZoomUpdateEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
Offset? pan,
Offset? localPan,
Offset? panDelta,
Offset? localPanDelta,
double? scale,
double? rotation,
}) {
assert(kind == null || identical(kind, PointerDeviceKind.trackpad));
return PointerPanZoomUpdateEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
device: device ?? this.device,
position: position ?? this.position,
embedderId: embedderId ?? this.embedderId,
pan: pan ?? this.pan,
panDelta: panDelta ?? this.panDelta,
scale: scale ?? this.scale,
rotation: rotation ?? this.rotation,
).transformed(transform);
}
}
/// The active pan/zoom on this pointer has updated.
///
/// See also:
///
/// * [Listener.onPointerPanZoomUpdate], which allows callers to be notified of these
/// events in a widget tree.
class PointerPanZoomUpdateEvent extends PointerEvent with _PointerEventDescription, _CopyPointerPanZoomUpdateEvent {
/// Creates a pointer pan/zoom update event.
const PointerPanZoomUpdateEvent({
super.viewId,
super.timeStamp,
super.device,
super.pointer,
super.position,
super.embedderId,
this.pan = Offset.zero,
this.panDelta = Offset.zero,
this.scale = 1.0,
this.rotation = 0.0,
super.synthesized,
}) : super(kind: PointerDeviceKind.trackpad);
@override
final Offset pan;
@override
Offset get localPan => pan;
@override
final Offset panDelta;
@override
Offset get localPanDelta => panDelta;
@override
final double scale;
@override
final double rotation;
@override
PointerPanZoomUpdateEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerPanZoomUpdateEvent(original as PointerPanZoomUpdateEvent? ?? this, transform);
}
}
class _TransformedPointerPanZoomUpdateEvent extends _TransformedPointerEvent with _CopyPointerPanZoomUpdateEvent implements PointerPanZoomUpdateEvent {
_TransformedPointerPanZoomUpdateEvent(this.original, this.transform);
@override
Offset get pan => original.pan;
@override
late final Offset localPan = PointerEvent.transformPosition(transform, pan);
@override
Offset get panDelta => original.panDelta;
@override
late final Offset localPanDelta = PointerEvent.transformDeltaViaPositions(
transform: transform,
untransformedDelta: panDelta,
untransformedEndPosition: pan,
transformedEndPosition: localPan,
);
@override
double get scale => original.scale;
@override
double get rotation => original.rotation;
@override
final PointerPanZoomUpdateEvent original;
@override
final Matrix4 transform;
@override
PointerPanZoomUpdateEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerPanZoomEndEvent on PointerEvent {
@override
PointerPanZoomEndEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
assert(kind == null || identical(kind, PointerDeviceKind.trackpad));
return PointerPanZoomEndEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
device: device ?? this.device,
position: position ?? this.position,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The pan/zoom on this pointer has ended.
///
/// See also:
///
/// * [Listener.onPointerPanZoomEnd], which allows callers to be notified of these
/// events in a widget tree.
class PointerPanZoomEndEvent extends PointerEvent with _PointerEventDescription, _CopyPointerPanZoomEndEvent {
/// Creates a pointer pan/zoom end event.
const PointerPanZoomEndEvent({
super.viewId,
super.timeStamp,
super.device,
super.pointer,
super.position,
super.embedderId,
super.synthesized,
}) : super(kind: PointerDeviceKind.trackpad);
@override
PointerPanZoomEndEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerPanZoomEndEvent(original as PointerPanZoomEndEvent? ?? this, transform);
}
}
class _TransformedPointerPanZoomEndEvent extends _TransformedPointerEvent with _CopyPointerPanZoomEndEvent implements PointerPanZoomEndEvent {
_TransformedPointerPanZoomEndEvent(this.original, this.transform);
@override
final PointerPanZoomEndEvent original;
@override
final Matrix4 transform;
@override
PointerPanZoomEndEvent transformed(Matrix4? transform) => original.transformed(transform);
}
mixin _CopyPointerCancelEvent on PointerEvent {
@override
PointerCancelEvent copyWith({
int? viewId,
Duration? timeStamp,
int? pointer,
PointerDeviceKind? kind,
int? device,
Offset? position,
Offset? delta,
int? buttons,
bool? obscured,
double? pressure,
double? pressureMin,
double? pressureMax,
double? distance,
double? distanceMax,
double? size,
double? radiusMajor,
double? radiusMinor,
double? radiusMin,
double? radiusMax,
double? orientation,
double? tilt,
bool? synthesized,
int? embedderId,
}) {
return PointerCancelEvent(
viewId: viewId ?? this.viewId,
timeStamp: timeStamp ?? this.timeStamp,
pointer: pointer ?? this.pointer,
kind: kind ?? this.kind,
device: device ?? this.device,
position: position ?? this.position,
buttons: buttons ?? this.buttons,
obscured: obscured ?? this.obscured,
pressureMin: pressureMin ?? this.pressureMin,
pressureMax: pressureMax ?? this.pressureMax,
distance: distance ?? this.distance,
distanceMax: distanceMax ?? this.distanceMax,
size: size ?? this.size,
radiusMajor: radiusMajor ?? this.radiusMajor,
radiusMinor: radiusMinor ?? this.radiusMinor,
radiusMin: radiusMin ?? this.radiusMin,
radiusMax: radiusMax ?? this.radiusMax,
orientation: orientation ?? this.orientation,
tilt: tilt ?? this.tilt,
embedderId: embedderId ?? this.embedderId,
).transformed(transform);
}
}
/// The input from the pointer is no longer directed towards this receiver.
///
/// See also:
///
/// * [Listener.onPointerCancel], which allows callers to be notified of these
/// events in a widget tree.
class PointerCancelEvent extends PointerEvent with _PointerEventDescription, _CopyPointerCancelEvent {
/// Creates a pointer cancel event.
const PointerCancelEvent({
super.viewId,
super.timeStamp,
super.pointer,
super.kind,
super.device,
super.position,
super.buttons,
super.obscured,
super.pressureMin,
super.pressureMax,
super.distance,
super.distanceMax,
super.size,
super.radiusMajor,
super.radiusMinor,
super.radiusMin,
super.radiusMax,
super.orientation,
super.tilt,
super.embedderId,
}) : assert(!identical(kind, PointerDeviceKind.trackpad)),
super(
down: false,
pressure: 0.0,
);
@override
PointerCancelEvent transformed(Matrix4? transform) {
if (transform == null || transform == this.transform) {
return this;
}
return _TransformedPointerCancelEvent(original as PointerCancelEvent? ?? this, transform);
}
}
/// Determine the appropriate hit slop pixels based on the [kind] of pointer.
double computeHitSlop(PointerDeviceKind kind, DeviceGestureSettings? settings) {
switch (kind) {
case PointerDeviceKind.mouse:
return kPrecisePointerHitSlop;
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
case PointerDeviceKind.unknown:
case PointerDeviceKind.touch:
case PointerDeviceKind.trackpad:
return settings?.touchSlop ?? kTouchSlop;
}
}
/// Determine the appropriate pan slop pixels based on the [kind] of pointer.
double computePanSlop(PointerDeviceKind kind, DeviceGestureSettings? settings) {
switch (kind) {
case PointerDeviceKind.mouse:
return kPrecisePointerPanSlop;
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
case PointerDeviceKind.unknown:
case PointerDeviceKind.touch:
case PointerDeviceKind.trackpad:
return settings?.panSlop ?? kPanSlop;
}
}
/// Determine the appropriate scale slop pixels based on the [kind] of pointer.
double computeScaleSlop(PointerDeviceKind kind) {
switch (kind) {
case PointerDeviceKind.mouse:
return kPrecisePointerScaleSlop;
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
case PointerDeviceKind.unknown:
case PointerDeviceKind.touch:
case PointerDeviceKind.trackpad:
return kScaleSlop;
}
}
class _TransformedPointerCancelEvent extends _TransformedPointerEvent with _CopyPointerCancelEvent implements PointerCancelEvent {
_TransformedPointerCancelEvent(this.original, this.transform);
@override
final PointerCancelEvent original;
@override
final Matrix4 transform;
@override
PointerCancelEvent transformed(Matrix4? transform) => original.transformed(transform);
}
| flutter/packages/flutter/lib/src/gestures/events.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/events.dart",
"repo_id": "flutter",
"token_count": 25353
} | 624 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.