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'; import '../../gallery/demo.dart'; class IconsDemo extends StatefulWidget { const IconsDemo({super.key}); static const String routeName = '/material/icons'; @override IconsDemoState createState() => IconsDemoState(); } class IconsDemoState extends State<IconsDemo> { static final List<MaterialColor> iconColors = <MaterialColor>[ Colors.red, Colors.pink, Colors.purple, Colors.deepPurple, Colors.indigo, Colors.blue, Colors.lightBlue, Colors.cyan, Colors.teal, Colors.green, Colors.lightGreen, Colors.lime, Colors.yellow, Colors.amber, Colors.orange, Colors.deepOrange, Colors.brown, Colors.grey, Colors.blueGrey, ]; int iconColorIndex = 8; // teal Color get iconColor => iconColors[iconColorIndex]; void handleIconButtonPress() { setState(() { iconColorIndex = (iconColorIndex + 1) % iconColors.length; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Icons'), actions: <Widget>[MaterialDemoDocumentationButton(IconsDemo.routeName)], ), body: IconTheme( data: IconThemeData(color: iconColor), child: SafeArea( top: false, bottom: false, child: Scrollbar( child: ListView( primary: true, padding: const EdgeInsets.all(24.0), children: <Widget>[ _IconsDemoCard(handleIconButtonPress, Icons.face), // direction-agnostic icon const SizedBox(height: 24.0), _IconsDemoCard(handleIconButtonPress, Icons.battery_unknown), // direction-aware icon ], ), ), ), ), ); } } class _IconsDemoCard extends StatelessWidget { const _IconsDemoCard(this.handleIconButtonPress, this.icon); final VoidCallback handleIconButtonPress; final IconData icon; Widget _buildIconButton(double iconSize, IconData icon, bool enabled) { return IconButton( icon: Icon(icon), iconSize: iconSize, tooltip: "${enabled ? 'Enabled' : 'Disabled'} icon button", onPressed: enabled ? handleIconButtonPress : null, ); } Widget _centeredText(String label) => Padding( // Match the default padding of IconButton. padding: const EdgeInsets.all(8.0), child: Text(label, textAlign: TextAlign.center), ); TableRow _buildIconRow(double size) { return TableRow( children: <Widget> [ _centeredText('${size.floor()} $icon'), _buildIconButton(size, icon, true), _buildIconButton(size, icon, false), ], ); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TextStyle textStyle = theme.textTheme.titleMedium!.copyWith(color: theme.textTheme.bodySmall!.color); return Card( child: DefaultTextStyle( style: textStyle, child: Semantics( explicitChildNodes: true, child: Table( defaultVerticalAlignment: TableCellVerticalAlignment.middle, children: <TableRow> [ TableRow( children: <Widget> [ _centeredText('Size $icon'), _centeredText('Enabled $icon'), _centeredText('Disabled $icon'), ] ), _buildIconRow(18.0), _buildIconRow(24.0), _buildIconRow(36.0), _buildIconRow(48.0), ], ), ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/icons_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/icons_demo.dart", "repo_id": "flutter", "token_count": 1656 }
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. import 'package:flutter/material.dart'; import '../../gallery/demo.dart'; // Each TabBarView contains a _Page and for each _Page there is a list // of _CardData objects. Each _CardData object is displayed by a _CardItem. const String _kGalleryAssetsPackage = 'flutter_gallery_assets'; class _Page { _Page({ this.label }); final String? label; String get id => label!.characters.first; @override String toString() => '$runtimeType("$label")'; } class _CardData { const _CardData({ this.title, this.imageAsset, this.imageAssetPackage }); final String? title; final String? imageAsset; final String? imageAssetPackage; } final Map<_Page, List<_CardData>> _allPages = <_Page, List<_CardData>>{ _Page(label: 'HOME'): <_CardData>[ const _CardData( title: 'Flatwear', imageAsset: 'products/flatwear.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Pine Table', imageAsset: 'products/table.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Blue Cup', imageAsset: 'products/cup.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Tea Set', imageAsset: 'products/teaset.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Desk Set', imageAsset: 'products/deskset.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Blue Linen Napkins', imageAsset: 'products/napkins.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Planters', imageAsset: 'products/planters.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Kitchen Quattro', imageAsset: 'products/kitchen_quattro.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Platter', imageAsset: 'products/platter.png', imageAssetPackage: _kGalleryAssetsPackage, ), ], _Page(label: 'APPAREL'): <_CardData>[ const _CardData( title: 'Cloud-White Dress', imageAsset: 'products/dress.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Ginger Scarf', imageAsset: 'products/scarf.png', imageAssetPackage: _kGalleryAssetsPackage, ), const _CardData( title: 'Blush Sweats', imageAsset: 'products/sweats.png', imageAssetPackage: _kGalleryAssetsPackage, ), ], }; class _CardDataItem extends StatelessWidget { const _CardDataItem({ this.page, this.data }); static const double height = 272.0; final _Page? page; final _CardData? data; @override Widget build(BuildContext context) { return Card( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Align( alignment: page!.id == 'H' ? Alignment.centerLeft : Alignment.centerRight, child: CircleAvatar(child: Text(page!.id)), ), SizedBox( width: 144.0, height: 144.0, child: Image.asset( data!.imageAsset!, package: data!.imageAssetPackage, fit: BoxFit.contain, ), ), Center( child: Text( data!.title!, style: Theme.of(context).textTheme.titleLarge, ), ), ], ), ), ); } } class TabsDemo extends StatelessWidget { const TabsDemo({super.key}); static const String routeName = '/material/tabs'; @override Widget build(BuildContext context) { return DefaultTabController( length: _allPages.length, child: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar( title: const Text('Tabs and scrolling'), actions: <Widget>[MaterialDemoDocumentationButton(routeName)], pinned: true, expandedHeight: 150.0, forceElevated: innerBoxIsScrolled, bottom: TabBar( tabs: _allPages.keys.map<Widget>( (_Page page) => Tab(text: page.label), ).toList(), ), ), ), ]; }, body: TabBarView( children: _allPages.keys.map<Widget>((_Page page) { return SafeArea( top: false, bottom: false, child: Builder( builder: (BuildContext context) { return CustomScrollView( key: PageStorageKey<_Page>(page), slivers: <Widget>[ SliverOverlapInjector( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), ), SliverPadding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 16.0, ), sliver: SliverFixedExtentList( itemExtent: _CardDataItem.height, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { final _CardData data = _allPages[page]![index]; return Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, ), child: _CardDataItem( page: page, data: data, ), ); }, childCount: _allPages[page]!.length, ), ), ), ], ); }, ), ); }).toList(), ), ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/tabs_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/tabs_demo.dart", "repo_id": "flutter", "token_count": 3563 }
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'; import '../model/product.dart'; import 'product_columns.dart'; class AsymmetricView extends StatelessWidget { const AsymmetricView({super.key, this.products}); final List<Product>? products; List<SizedBox> _buildColumns(BuildContext context) { if (products == null || products!.isEmpty) { return const <SizedBox>[]; } // This will return a list of columns. It will oscillate between the two // kinds of columns. Even cases of the index (0, 2, 4, etc) will be // TwoProductCardColumn and the odd cases will be OneProductCardColumn. // // Each pair of columns will advance us 3 products forward (2 + 1). That's // some kinda awkward math so we use _evenCasesIndex and _oddCasesIndex as // helpers for creating the index of the product list that will correspond // to the index of the list of columns. return List<SizedBox>.generate(_listItemCount(products!.length), (int index) { double width = .59 * MediaQuery.of(context).size.width; Widget column; if (index.isEven) { /// Even cases final int bottom = _evenCasesIndex(index); column = TwoProductCardColumn( bottom: products![bottom], top: products!.length - 1 >= bottom + 1 ? products![bottom + 1] : null, ); width += 32.0; } else { /// Odd cases column = OneProductCardColumn( product: products![_oddCasesIndex(index)], ); } return SizedBox( width: width, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: column, ), ); }).toList(); } int _evenCasesIndex(int input) { // The operator ~/ is a cool one. It's the truncating division operator. It // divides the number and if there's a remainder / decimal, it cuts it off. // This is like dividing and then casting the result to int. Also, it's // functionally equivalent to floor() in this case. return input ~/ 2 * 3; } int _oddCasesIndex(int input) { assert(input > 0); return (input / 2).ceil() * 3 - 1; } int _listItemCount(int totalItems) { return (totalItems % 3 == 0) ? totalItems ~/ 3 * 2 : (totalItems / 3).ceil() * 2 - 1; } @override Widget build(BuildContext context) { return ListView( scrollDirection: Axis.horizontal, padding: const EdgeInsets.fromLTRB(0.0, 34.0, 16.0, 44.0), physics: const AlwaysScrollableScrollPhysics(), children: _buildColumns(context), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/asymmetric_view.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/asymmetric_view.dart", "repo_id": "flutter", "token_count": 1039 }
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 'dart:math' as math; import 'package:flutter/material.dart'; const double _kFrontHeadingHeight = 32.0; // front layer beveled rectangle const double _kFrontClosedHeight = 92.0; // front layer height when closed const double _kBackAppBarHeight = 56.0; // back layer (options) appbar height // The size of the front layer heading's left and right beveled corners. final Animatable<BorderRadius?> _kFrontHeadingBevelRadius = BorderRadiusTween( begin: const BorderRadius.only( topLeft: Radius.circular(12.0), topRight: Radius.circular(12.0), ), end: const BorderRadius.only( topLeft: Radius.circular(_kFrontHeadingHeight), topRight: Radius.circular(_kFrontHeadingHeight), ), ); class _TappableWhileStatusIs extends StatefulWidget { const _TappableWhileStatusIs( this.status, { this.controller, this.child, }); final AnimationController? controller; final AnimationStatus status; final Widget? child; @override _TappableWhileStatusIsState createState() => _TappableWhileStatusIsState(); } class _TappableWhileStatusIsState extends State<_TappableWhileStatusIs> { bool? _active; @override void initState() { super.initState(); widget.controller!.addStatusListener(_handleStatusChange); _active = widget.controller!.status == widget.status; } @override void dispose() { widget.controller!.removeStatusListener(_handleStatusChange); super.dispose(); } void _handleStatusChange(AnimationStatus status) { final bool value = widget.controller!.status == widget.status; if (_active != value) { setState(() { _active = value; }); } } @override Widget build(BuildContext context) { Widget child = AbsorbPointer( absorbing: !_active!, child: widget.child, ); if (!_active!) { child = FocusScope( canRequestFocus: false, debugLabel: '$_TappableWhileStatusIs', child: child, ); } return child; } } class _CrossFadeTransition extends AnimatedWidget { const _CrossFadeTransition({ this.alignment = Alignment.center, required Animation<double> progress, this.child0, this.child1, }) : super(listenable: progress); final AlignmentGeometry alignment; final Widget? child0; final Widget? child1; @override Widget build(BuildContext context) { final Animation<double> progress = listenable as Animation<double>; final double opacity1 = CurvedAnimation( parent: ReverseAnimation(progress), curve: const Interval(0.5, 1.0), ).value; final double opacity2 = CurvedAnimation( parent: progress, curve: const Interval(0.5, 1.0), ).value; return Stack( alignment: alignment, children: <Widget>[ Opacity( opacity: opacity1, child: Semantics( scopesRoute: true, explicitChildNodes: true, child: child1, ), ), Opacity( opacity: opacity2, child: Semantics( scopesRoute: true, explicitChildNodes: true, child: child0, ), ), ], ); } } class _BackAppBar extends StatelessWidget { const _BackAppBar({ this.leading = const SizedBox(width: 56.0), required this.title, this.trailing, }); final Widget leading; final Widget title; final Widget? trailing; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return IconTheme.merge( data: theme.primaryIconTheme, child: DefaultTextStyle( style: theme.primaryTextTheme.titleLarge!, child: SizedBox( height: _kBackAppBarHeight, child: Row( children: <Widget>[ Container( alignment: Alignment.center, width: 56.0, child: leading, ), Expanded( child: title, ), if (trailing != null) Container( alignment: Alignment.center, width: 56.0, child: trailing, ), ], ), ), ), ); } } class Backdrop extends StatefulWidget { const Backdrop({ super.key, this.frontAction, this.frontTitle, this.frontHeading, this.frontLayer, this.backTitle, this.backLayer, }); final Widget? frontAction; final Widget? frontTitle; final Widget? frontLayer; final Widget? frontHeading; final Widget? backTitle; final Widget? backLayer; @override State<Backdrop> createState() => _BackdropState(); } class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin { final GlobalKey _backdropKey = GlobalKey(debugLabel: 'Backdrop'); AnimationController? _controller; late Animation<double> _frontOpacity; static final Animatable<double> _frontOpacityTween = Tween<double>(begin: 0.2, end: 1.0) .chain(CurveTween(curve: const Interval(0.0, 0.4, curve: Curves.easeInOut))); @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 300), value: 1.0, vsync: this, ); _controller!.addStatusListener((AnimationStatus status) { setState(() { // This is intentionally left empty. The state change itself takes // place inside the AnimationController, so there's nothing to update. // All we want is for the widget to rebuild and read the new animation // state from the AnimationController. }); }); _frontOpacity = _controller!.drive(_frontOpacityTween); } @override void dispose() { _controller!.dispose(); super.dispose(); } double get _backdropHeight { // Warning: this can be safely called from the event handlers but it may // not be called at build time. final RenderBox renderBox = _backdropKey.currentContext!.findRenderObject()! as RenderBox; return math.max(0.0, renderBox.size.height - _kBackAppBarHeight - _kFrontClosedHeight); } void _handleDragUpdate(DragUpdateDetails details) { _controller!.value -= details.primaryDelta! / _backdropHeight; } void _handleDragEnd(DragEndDetails details) { if (_controller!.isAnimating || _controller!.status == AnimationStatus.completed) { return; } final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight; if (flingVelocity < 0.0) { _controller!.fling(velocity: math.max(2.0, -flingVelocity)); } else if (flingVelocity > 0.0) { _controller!.fling(velocity: math.min(-2.0, -flingVelocity)); } else { _controller!.fling(velocity: _controller!.value < 0.5 ? -2.0 : 2.0); } } void _toggleFrontLayer() { final AnimationStatus status = _controller!.status; final bool isOpen = status == AnimationStatus.completed || status == AnimationStatus.forward; _controller!.fling(velocity: isOpen ? -2.0 : 2.0); } Widget _buildStack(BuildContext context, BoxConstraints constraints) { final Animation<RelativeRect> frontRelativeRect = _controller!.drive(RelativeRectTween( begin: RelativeRect.fromLTRB(0.0, constraints.biggest.height - _kFrontClosedHeight, 0.0, 0.0), end: const RelativeRect.fromLTRB(0.0, _kBackAppBarHeight, 0.0, 0.0), )); return Stack( key: _backdropKey, children: <Widget>[ // Back layer Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _BackAppBar( leading: widget.frontAction!, title: _CrossFadeTransition( progress: _controller!, alignment: AlignmentDirectional.centerStart, child0: Semantics(namesRoute: true, child: widget.frontTitle), child1: Semantics(namesRoute: true, child: widget.backTitle), ), trailing: IconButton( onPressed: _toggleFrontLayer, tooltip: 'Toggle options page', icon: AnimatedIcon( icon: AnimatedIcons.close_menu, progress: _controller!, ), ), ), Expanded( child: _TappableWhileStatusIs( AnimationStatus.dismissed, controller: _controller, child: Visibility( visible: _controller!.status != AnimationStatus.completed, maintainState: true, child: widget.backLayer!, ), ), ), ], ), // Front layer PositionedTransition( rect: frontRelativeRect, child: AnimatedBuilder( animation: _controller!, builder: (BuildContext context, Widget? child) { return PhysicalShape( elevation: 12.0, color: Theme.of(context).canvasColor, clipper: ShapeBorderClipper( shape: BeveledRectangleBorder( borderRadius: _kFrontHeadingBevelRadius.transform(_controller!.value)!, ), ), clipBehavior: Clip.antiAlias, child: child, ); }, child: _TappableWhileStatusIs( AnimationStatus.completed, controller: _controller, child: FadeTransition( opacity: _frontOpacity, child: widget.frontLayer, ), ), ), ), // The front "heading" is a (typically transparent) widget that's stacked on // top of, and at the top of, the front layer. It adds support for dragging // the front layer up and down and for opening and closing the front layer // with a tap. It may obscure part of the front layer's topmost child. if (widget.frontHeading != null) PositionedTransition( rect: frontRelativeRect, child: ExcludeSemantics( child: Container( alignment: Alignment.topLeft, child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: _toggleFrontLayer, onVerticalDragUpdate: _handleDragUpdate, onVerticalDragEnd: _handleDragEnd, child: widget.frontHeading, ), ), ), ), ], ); } @override Widget build(BuildContext context) { return LayoutBuilder(builder: _buildStack); } }
flutter/dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart", "repo_id": "flutter", "token_count": 4664 }
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 <FlutterMacOS/FlutterMacOS.h> #import <XCTest/XCTest.h> @interface RunnerTests : XCTestCase @end @implementation RunnerTests - (void)testMenu { NSMenu *applicationMenu = ((FlutterAppDelegate *)NSApplication.sharedApplication.delegate).applicationMenu; XCTAssertEqual(applicationMenu.numberOfItems, 11); XCTAssertEqualObjects([applicationMenu itemAtIndex:0].title, @"About Flutter Gallery"); NSMenu *mainMenu = NSApplication.sharedApplication.mainMenu; XCTAssertEqual([mainMenu indexOfItemWithSubmenu:applicationMenu], 0); // The number of submenu items changes depending on what the OS decides to inject. // Just check there's at least one per menu item. XCTAssertGreaterThanOrEqual([mainMenu itemWithTitle:@"Edit"].submenu.numberOfItems, 1); XCTAssertGreaterThanOrEqual([mainMenu itemWithTitle:@"View"].submenu.numberOfItems, 1); XCTAssertGreaterThanOrEqual([mainMenu itemWithTitle:@"Window"].submenu.numberOfItems, 1); NSMenu *helpMenu = NSApplication.sharedApplication.helpMenu; XCTAssertNotNil(helpMenu); // Only the help menu search text box. XCTAssertEqual(helpMenu.numberOfItems, 0); } @end
flutter/dev/integration_tests/flutter_gallery/macos/RunnerTests/RunnerTests.m/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/macos/RunnerTests/RunnerTests.m", "repo_id": "flutter", "token_count": 420 }
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. // ATTENTION! // // This file is not named "*_test.dart", and as such will not run when you run // "flutter test". It is only intended to be run as part of the // flutter_gallery_instrumentation_test devicelab test. import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart' show PointerDeviceKind, kPrimaryButton; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gallery/gallery/app.dart' show GalleryApp; import 'package:flutter_gallery/gallery/demos.dart'; import 'package:flutter_test/flutter_test.dart'; // Reports success or failure to the native code. const MethodChannel _kTestChannel = MethodChannel('io.flutter.demo.gallery/TestLifecycleListener'); // We don't want to wait for animations to complete before tapping the // back button in the demos with these titles. const List<String> _kUnsynchronizedDemoTitles = <String>[ 'Progress indicators', 'Activity Indicator', 'Video', ]; // These demos can't be backed out of by tapping a button whose // tooltip is 'Back'. const List<String> _kSkippedDemoTitles = <String>[ 'Progress indicators', 'Activity Indicator', 'Video', ]; // There are 3 places where the Gallery demos are traversed. // 1- In widget tests such as dev/integration_tests/flutter_gallery/test/smoke_test.dart // 2- In driver tests such as dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart // 3- In on-device instrumentation tests such as dev/integration_tests/flutter_gallery/test/live_smoketest.dart // // If you change navigation behavior in the Gallery or in the framework, make // sure all 3 are covered. Future<void> main() async { try { // Verify that _kUnsynchronizedDemos and _kSkippedDemos identify // demos that actually exist. final List<String> allDemoTitles = kAllGalleryDemos.map((GalleryDemo demo) => demo.title).toList(); if (!Set<String>.from(allDemoTitles).containsAll(_kUnsynchronizedDemoTitles)) { fail('Unrecognized demo titles in _kUnsynchronizedDemosTitles: $_kUnsynchronizedDemoTitles'); } if (!Set<String>.from(allDemoTitles).containsAll(_kSkippedDemoTitles)) { fail('Unrecognized demo names in _kSkippedDemoTitles: $_kSkippedDemoTitles'); } print('Starting app...'); runApp(const GalleryApp(testMode: true)); final _LiveWidgetController controller = _LiveWidgetController(WidgetsBinding.instance); for (final GalleryDemoCategory category in kAllGalleryDemoCategories) { print('Tapping "${category.name}" section...'); await controller.tap(find.text(category.name)); for (final GalleryDemo demo in kGalleryCategoryToDemos[category]!) { final Finder demoItem = find.text(demo.title); print('Scrolling to "${demo.title}"...'); await controller.scrollIntoView(demoItem, alignment: 0.5); if (_kSkippedDemoTitles.contains(demo.title)) { continue; } for (int i = 0; i < 2; i += 1) { print('Tapping "${demo.title}"...'); await controller.tap(demoItem); // Launch the demo controller.frameSync = !_kUnsynchronizedDemoTitles.contains(demo.title); print('Going back to demo list...'); await controller.tap(backFinder); controller.frameSync = true; } } print('Going back to home screen...'); await controller.tap(find.byTooltip('Back')); } print('Finished successfully!'); _kTestChannel.invokeMethod<void>('success'); } catch (error, stack) { print('Caught error: $error\n$stack'); _kTestChannel.invokeMethod<void>('failure'); } } final Finder backFinder = find.byElementPredicate( (Element element) { final Widget widget = element.widget; if (widget is Tooltip) { return widget.message == 'Back'; } if (widget is CupertinoNavigationBarBackButton) { return true; } return false; }, description: 'Material or Cupertino back button', ); class _LiveWidgetController extends LiveWidgetController { _LiveWidgetController(super.binding); /// With [frameSync] enabled, Flutter Driver will wait to perform an action /// until there are no pending frames in the app under test. bool frameSync = true; /// Waits until at the end of a frame the provided [condition] is [true]. Future<void> _waitUntilFrame(bool Function() condition, [Completer<void>? completer]) { completer ??= Completer<void>(); if (!condition()) { SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) { _waitUntilFrame(condition, completer); }); } else { completer.complete(); } return completer.future; } /// Runs `finder` repeatedly until it finds one or more [Element]s. Future<FinderBase<Element>> _waitForElement(FinderBase<Element> finder) async { if (frameSync) { await _waitUntilFrame(() => binding.transientCallbackCount == 0); } await _waitUntilFrame(() => finder.tryEvaluate()); if (frameSync) { await _waitUntilFrame(() => binding.transientCallbackCount == 0); } return finder; } Future<void> scrollIntoView(FinderBase<Element> finder, {required double alignment}) async { final FinderBase<Element> target = await _waitForElement(finder); await Scrollable.ensureVisible(target.evaluate().single, duration: const Duration(milliseconds: 100), alignment: alignment); } @override Future<void> tap(FinderBase<Element> finder, { int? pointer, int buttons = kPrimaryButton, bool warnIfMissed = true, PointerDeviceKind kind = PointerDeviceKind.touch, }) async { await super.tap(await _waitForElement(finder), pointer: pointer, buttons: buttons, warnIfMissed: warnIfMissed, kind: kind); } }
flutter/dev/integration_tests/flutter_gallery/test/live_smoketest.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/live_smoketest.dart", "repo_id": "flutter", "token_count": 2040 }
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. package io.flutter.integration.platformviews; import android.annotation.TargetApi; import android.os.Build; import android.view.MotionEvent; import android.view.View; import io.flutter.plugin.common.MethodChannel; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) class TouchPipe implements View.OnTouchListener { private final MethodChannel mMethodChannel; private final View mView; private boolean mEnabled; TouchPipe(MethodChannel methodChannel, View view) { mMethodChannel = methodChannel; mView = view; } public void enable() { if (mEnabled) return; mEnabled = true; mView.setOnTouchListener(this); } public void disable() { if (!mEnabled) return; mEnabled = false; mView.setOnTouchListener(null); } @Override public boolean onTouch(View v, MotionEvent event) { mMethodChannel.invokeMethod("onTouch", MotionEventCodec.encode(event)); return false; } }
flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/TouchPipe.java/0
{ "file_path": "flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/TouchPipe.java", "repo_id": "flutter", "token_count": 438 }
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'; /// The base class of all the testing pages // /// A testing page has to override this in order to be put as one of the items in the main page. abstract class PageWidget extends StatelessWidget { const PageWidget(this.title, this.tileKey, {super.key}); /// The title of the testing page /// /// It will be shown on the main page as the text on the link which opens the page. final String title; /// The key of the ListTile that navigates to the page. /// /// Used by the integration test to navigate to the corresponding page. final ValueKey<String> tileKey; }
flutter/dev/integration_tests/hybrid_android_views/lib/page.dart/0
{ "file_path": "flutter/dev/integration_tests/hybrid_android_views/lib/page.dart", "repo_id": "flutter", "token_count": 210 }
578
<?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> <FileRef location = "group:ios_add2app.xcodeproj"> </FileRef> <FileRef location = "group:Pods/Pods.xcodeproj"> </FileRef> </Workspace>
flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2app.xcworkspace/contents.xcworkspacedata/0
{ "file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2app.xcworkspace/contents.xcworkspacedata", "repo_id": "flutter", "token_count": 107 }
579
# iOS Extensions Test Integration test to test building an iOS app with non-Flutter features: - watchOS app and extension
flutter/dev/integration_tests/ios_app_with_extensions/README.md/0
{ "file_path": "flutter/dev/integration_tests/ios_app_with_extensions/README.md", "repo_id": "flutter", "token_count": 31 }
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/cupertino.dart'; import 'package:flutter/material.dart'; import '../../gallery_localizations.dart'; // BEGIN cupertinoNavigationBarDemo class CupertinoNavigationBarDemo extends StatelessWidget { const CupertinoNavigationBarDemo({super.key}); static const String homeRoute = '/home'; static const String secondPageRoute = '/home/item'; @override Widget build(BuildContext context) { return Navigator( restorationScopeId: 'navigator', initialRoute: CupertinoNavigationBarDemo.homeRoute, onGenerateRoute: (RouteSettings settings) { switch (settings.name) { case CupertinoNavigationBarDemo.homeRoute: return _NoAnimationCupertinoPageRoute<void>( title: GalleryLocalizations.of(context)! .demoCupertinoNavigationBarTitle, settings: settings, builder: (BuildContext context) => _FirstPage(), ); case CupertinoNavigationBarDemo.secondPageRoute: final Map<dynamic, dynamic> arguments = settings.arguments! as Map<dynamic, dynamic>; final String? title = arguments['pageTitle'] as String?; return CupertinoPageRoute<void>( title: title, settings: settings, builder: (BuildContext context) => _SecondPage(), ); } return null; }, ); } } class _FirstPage extends StatelessWidget { @override Widget build(BuildContext context) { return CupertinoPageScaffold( child: CustomScrollView( slivers: <Widget>[ const CupertinoSliverNavigationBar( automaticallyImplyLeading: false, ), SliverPadding( padding: MediaQuery.of(context).removePadding(removeTop: true).padding, sliver: SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { final String title = GalleryLocalizations.of(context)! .starterAppDrawerItem(index + 1); return ListTile( onTap: () { Navigator.of(context).restorablePushNamed<void>( CupertinoNavigationBarDemo.secondPageRoute, arguments: <String, String>{'pageTitle': title}, ); }, title: Text(title), ); }, childCount: 20, ), ), ), ], ), ); } } class _SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar(), child: Container(), ); } } /// A CupertinoPageRoute without any transition animations. class _NoAnimationCupertinoPageRoute<T> extends CupertinoPageRoute<T> { _NoAnimationCupertinoPageRoute({ required super.builder, super.settings, super.title, }); @override Widget buildTransitions( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { return child; } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_navigation_bar_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_navigation_bar_demo.dart", "repo_id": "flutter", "token_count": 1504 }
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'; import '../../gallery_localizations.dart'; // BEGIN typographyDemo class _TextStyleItem extends StatelessWidget { const _TextStyleItem({ required this.name, required this.style, required this.text, }); final String name; final TextStyle style; final String text; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), child: Row( children: <Widget>[ SizedBox( width: 72, child: Text(name, style: Theme.of(context).textTheme.bodySmall), ), Expanded( child: Text(text, style: style), ), ], ), ); } } class TypographyDemo extends StatelessWidget { const TypographyDemo({super.key}); @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final List<_TextStyleItem> styleItems = <_TextStyleItem>[ _TextStyleItem( name: 'Headline 1', style: textTheme.displayLarge!, text: 'Light 96sp', ), _TextStyleItem( name: 'Headline 2', style: textTheme.displayMedium!, text: 'Light 60sp', ), _TextStyleItem( name: 'Headline 3', style: textTheme.displaySmall!, text: 'Regular 48sp', ), _TextStyleItem( name: 'Headline 4', style: textTheme.headlineMedium!, text: 'Regular 34sp', ), _TextStyleItem( name: 'Headline 5', style: textTheme.headlineSmall!, text: 'Regular 24sp', ), _TextStyleItem( name: 'Headline 6', style: textTheme.titleLarge!, text: 'Medium 20sp', ), _TextStyleItem( name: 'Subtitle 1', style: textTheme.titleMedium!, text: 'Regular 16sp', ), _TextStyleItem( name: 'Subtitle 2', style: textTheme.titleSmall!, text: 'Medium 14sp', ), _TextStyleItem( name: 'Body Text 1', style: textTheme.bodyLarge!, text: 'Regular 16sp', ), _TextStyleItem( name: 'Body Text 2', style: textTheme.bodyMedium!, text: 'Regular 14sp', ), _TextStyleItem( name: 'Button', style: textTheme.labelLarge!, text: 'MEDIUM (ALL CAPS) 14sp', ), _TextStyleItem( name: 'Caption', style: textTheme.bodySmall!, text: 'Regular 12sp', ), _TextStyleItem( name: 'Overline', style: textTheme.labelSmall!, text: 'REGULAR (ALL CAPS) 10sp', ), ]; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text(GalleryLocalizations.of(context)!.demoTypographyTitle), ), body: Scrollbar(child: ListView(children: styleItems)), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/reference/typography_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/reference/typography_demo.dart", "repo_id": "flutter", "token_count": 1398 }
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'; import '../constants.dart'; import '../data/demos.dart'; import '../gallery_localizations.dart'; import '../layout/adaptive.dart'; import 'demo.dart'; typedef CategoryHeaderTapCallback = void Function(bool shouldOpenList); class CategoryListItem extends StatefulWidget { const CategoryListItem({ super.key, this.restorationId, required this.category, required this.imageString, this.demos = const <GalleryDemo>[], this.initiallyExpanded = false, this.onTap, }); final GalleryDemoCategory category; final String? restorationId; final String imageString; final List<GalleryDemo> demos; final bool initiallyExpanded; final CategoryHeaderTapCallback? onTap; @override State<CategoryListItem> createState() => _CategoryListItemState(); } class _CategoryListItemState extends State<CategoryListItem> with SingleTickerProviderStateMixin { static final Animatable<double> _easeInTween = CurveTween(curve: Curves.easeIn); static const Duration _expandDuration = Duration(milliseconds: 200); late AnimationController _controller; late Animation<double> _childrenHeightFactor; late Animation<double> _headerChevronOpacity; late Animation<double> _headerHeight; late Animation<EdgeInsetsGeometry> _headerMargin; late Animation<EdgeInsetsGeometry> _headerImagePadding; late Animation<EdgeInsetsGeometry> _childrenPadding; late Animation<BorderRadius?> _headerBorderRadius; @override void initState() { super.initState(); _controller = AnimationController(duration: _expandDuration, vsync: this); _controller.addStatusListener((AnimationStatus status) { setState(() {}); }); _childrenHeightFactor = _controller.drive(_easeInTween); _headerChevronOpacity = _controller.drive(_easeInTween); _headerHeight = Tween<double>( begin: 80, end: 96, ).animate(_controller); _headerMargin = EdgeInsetsGeometryTween( begin: const EdgeInsets.fromLTRB(32, 8, 32, 8), end: EdgeInsets.zero, ).animate(_controller); _headerImagePadding = EdgeInsetsGeometryTween( begin: const EdgeInsets.all(8), end: const EdgeInsetsDirectional.fromSTEB(16, 8, 8, 8), ).animate(_controller); _childrenPadding = EdgeInsetsGeometryTween( begin: const EdgeInsets.symmetric(horizontal: 32), end: EdgeInsets.zero, ).animate(_controller); _headerBorderRadius = BorderRadiusTween( begin: BorderRadius.circular(10), end: BorderRadius.zero, ).animate(_controller); if (widget.initiallyExpanded) { _controller.value = 1.0; } } @override void dispose() { _controller.dispose(); super.dispose(); } bool _shouldOpenList() { switch (_controller.status) { case AnimationStatus.completed: case AnimationStatus.forward: case AnimationStatus.reverse: return false; case AnimationStatus.dismissed: return true; } } void _handleTap() { if (_shouldOpenList()) { _controller.forward(); if (widget.onTap != null) { widget.onTap!(true); } } else { _controller.reverse(); if (widget.onTap != null) { widget.onTap!(false); } } } Widget _buildHeaderWithChildren(BuildContext context, Widget? child) { return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ _CategoryHeader( margin: _headerMargin.value, imagePadding: _headerImagePadding.value, borderRadius: _headerBorderRadius.value!, height: _headerHeight.value, chevronOpacity: _headerChevronOpacity.value, imageString: widget.imageString, category: widget.category, onTap: _handleTap, ), Padding( padding: _childrenPadding.value, child: ClipRect( child: Align( heightFactor: _childrenHeightFactor.value, child: child, ), ), ), ], ); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller.view, builder: _buildHeaderWithChildren, child: _shouldOpenList() ? null : _ExpandedCategoryDemos( category: widget.category, demos: widget.demos, ), ); } } class _CategoryHeader extends StatelessWidget { const _CategoryHeader({ this.margin, required this.imagePadding, required this.borderRadius, this.height, required this.chevronOpacity, required this.imageString, required this.category, this.onTap, }); final EdgeInsetsGeometry? margin; final EdgeInsetsGeometry imagePadding; final double? height; final BorderRadiusGeometry borderRadius; final String imageString; final GalleryDemoCategory category; final double chevronOpacity; final GestureTapCallback? onTap; @override Widget build(BuildContext context) { final ColorScheme colorScheme = Theme.of(context).colorScheme; return Container( margin: margin, child: Material( shape: RoundedRectangleBorder(borderRadius: borderRadius), color: colorScheme.onBackground, clipBehavior: Clip.antiAlias, child: SizedBox( width: MediaQuery.of(context).size.width, child: InkWell( // Makes integration tests possible. key: ValueKey<String>('${category.name}CategoryHeader'), onTap: onTap, child: Row( children: <Widget>[ Expanded( child: Wrap( crossAxisAlignment: WrapCrossAlignment.center, children: <Widget>[ Padding( padding: imagePadding, child: FadeInImage( image: AssetImage( imageString, package: 'flutter_gallery_assets', ), placeholder: MemoryImage(kTransparentImage), fadeInDuration: entranceAnimationDuration, width: 64, height: 64, excludeFromSemantics: true, ), ), Padding( padding: const EdgeInsetsDirectional.only(start: 8), child: Text( category.displayTitle( GalleryLocalizations.of(context)!, )!, style: Theme.of(context).textTheme.headlineSmall!.apply( color: colorScheme.onSurface, ), ), ), ], ), ), Opacity( opacity: chevronOpacity, child: chevronOpacity != 0 ? Padding( padding: const EdgeInsetsDirectional.only( start: 8, end: 32, ), child: Icon( Icons.keyboard_arrow_up, color: colorScheme.onSurface, ), ) : null, ), ], ), ), ), ), ); } } class _ExpandedCategoryDemos extends StatelessWidget { const _ExpandedCategoryDemos({ required this.category, required this.demos, }); final GalleryDemoCategory category; final List<GalleryDemo> demos; @override Widget build(BuildContext context) { return Column( // Makes integration tests possible. key: ValueKey<String>('${category.name}DemoList'), children: <Widget>[ for (final GalleryDemo demo in demos) CategoryDemoItem( demo: demo, ), const SizedBox(height: 12), // Extra space below. ], ); } } class CategoryDemoItem extends StatelessWidget { const CategoryDemoItem({super.key, required this.demo}); final GalleryDemo demo; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final ColorScheme colorScheme = Theme.of(context).colorScheme; return Material( // Makes integration tests possible. key: ValueKey<String>(demo.describe), color: Theme.of(context).colorScheme.surface, child: MergeSemantics( child: InkWell( onTap: () { Navigator.of(context).restorablePushNamed( '${DemoPage.baseRoute}/${demo.slug}', ); }, child: Padding( padding: EdgeInsetsDirectional.only( start: 32, top: 20, end: isDisplayDesktop(context) ? 16 : 8, ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Icon( demo.icon, color: colorScheme.primary, ), const SizedBox(width: 40), Flexible( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( demo.title, style: textTheme.titleMedium! .apply(color: colorScheme.onSurface), ), Text( demo.subtitle, style: textTheme.labelSmall!.apply( color: colorScheme.onSurface.withOpacity(0.5), ), ), const SizedBox(height: 20), Divider( thickness: 1, height: 1, color: Theme.of(context).colorScheme.background, ), ], ), ), ], ), ), ), ), ); } }
flutter/dev/integration_tests/new_gallery/lib/pages/category_list_item.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/category_list_item.dart", "repo_id": "flutter", "token_count": 5195 }
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'; import '../../layout/adaptive.dart'; import 'colors.dart'; const double textFieldHeight = 60.0; const double appPaddingLarge = 120.0; const double appPaddingSmall = 24.0; class HeaderFormField { const HeaderFormField({ required this.index, required this.iconData, required this.title, required this.textController, }); final int index; final IconData iconData; final String title; final TextEditingController textController; } class HeaderForm extends StatelessWidget { const HeaderForm({super.key, required this.fields}); final List<HeaderFormField> fields; @override Widget build(BuildContext context) { final bool isDesktop = isDisplayDesktop(context); final bool isSmallDesktop = isDisplaySmallDesktop(context); return Padding( padding: EdgeInsets.symmetric( horizontal: isDesktop && !isSmallDesktop ? appPaddingLarge : appPaddingSmall, ), child: isDesktop ? LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { int crossAxisCount = isSmallDesktop ? 2 : 4; if (fields.length < crossAxisCount) { crossAxisCount = fields.length; } final double itemWidth = constraints.maxWidth / crossAxisCount; return GridView.count( crossAxisCount: crossAxisCount, childAspectRatio: itemWidth / textFieldHeight, physics: const NeverScrollableScrollPhysics(), children: <Widget>[ for (final HeaderFormField field in fields) if ((field.index + 1) % crossAxisCount == 0) _HeaderTextField(field: field) else Padding( padding: const EdgeInsetsDirectional.only(end: 16), child: _HeaderTextField(field: field), ), ], ); }) : Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ for (final HeaderFormField field in fields) Padding( padding: const EdgeInsets.only(bottom: 8), child: _HeaderTextField(field: field), ) ], ), ); } } class _HeaderTextField extends StatelessWidget { const _HeaderTextField({required this.field}); final HeaderFormField field; @override Widget build(BuildContext context) { return TextField( controller: field.textController, cursorColor: Theme.of(context).colorScheme.secondary, style: Theme.of(context).textTheme.bodyLarge!.copyWith(color: Colors.white), onTap: () {}, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide.none, ), contentPadding: const EdgeInsets.all(16), fillColor: cranePurple700, filled: true, hintText: field.title, floatingLabelBehavior: FloatingLabelBehavior.never, prefixIcon: Icon( field.iconData, size: 24, color: Theme.of(context).iconTheme.color, ), ), ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/crane/header_form.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/header_form.dart", "repo_id": "flutter", "token_count": 1542 }
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'; import '../../gallery_localizations.dart'; import 'formatters.dart'; /// Calculates the sum of the primary amounts of a list of [AccountData]. double sumAccountDataPrimaryAmount(List<AccountData> items) => sumOf<AccountData>(items, (AccountData item) => item.primaryAmount); /// Calculates the sum of the primary amounts of a list of [BillData]. double sumBillDataPrimaryAmount(List<BillData> items) => sumOf<BillData>(items, (BillData item) => item.primaryAmount); /// Calculates the sum of the primary amounts of a list of [BillData]. double sumBillDataPaidAmount(List<BillData> items) => sumOf<BillData>( items.where((BillData item) => item.isPaid).toList(), (BillData item) => item.primaryAmount, ); /// Calculates the sum of the primary amounts of a list of [BudgetData]. double sumBudgetDataPrimaryAmount(List<BudgetData> items) => sumOf<BudgetData>(items, (BudgetData item) => item.primaryAmount); /// Calculates the sum of the amounts used of a list of [BudgetData]. double sumBudgetDataAmountUsed(List<BudgetData> items) => sumOf<BudgetData>(items, (BudgetData item) => item.amountUsed); /// Utility function to sum up values in a list. double sumOf<T>(List<T> list, double Function(T elt) getValue) { double sum = 0.0; for (final T elt in list) { sum += getValue(elt); } return sum; } /// A data model for an account. /// /// The [primaryAmount] is the balance of the account in USD. class AccountData { const AccountData({ required this.name, required this.primaryAmount, required this.accountNumber, }); /// The display name of this entity. final String name; /// The primary amount or value of this entity. final double primaryAmount; /// The full displayable account number. final String accountNumber; } /// A data model for a bill. /// /// The [primaryAmount] is the amount due in USD. class BillData { const BillData({ required this.name, required this.primaryAmount, required this.dueDate, this.isPaid = false, }); /// The display name of this entity. final String name; /// The primary amount or value of this entity. final double primaryAmount; /// The due date of this bill. final String dueDate; /// If this bill has been paid. final bool isPaid; } /// A data model for a budget. /// /// The [primaryAmount] is the budget cap in USD. class BudgetData { const BudgetData({ required this.name, required this.primaryAmount, required this.amountUsed, }); /// The display name of this entity. final String name; /// The primary amount or value of this entity. final double primaryAmount; /// Amount of the budget that is consumed or used. final double amountUsed; } /// A data model for an alert. class AlertData { AlertData({this.message, this.iconData}); /// The alert message to display. final String? message; /// The icon to display with the alert. final IconData? iconData; } class DetailedEventData { const DetailedEventData({ required this.title, required this.date, required this.amount, }); final String title; final DateTime date; final double amount; } /// A data model for data displayed to the user. class UserDetailData { UserDetailData({ required this.title, required this.value, }); /// The display name of this entity. final String title; /// The value of this entity. final String value; } /// Class to return dummy data lists. /// /// In a real app, this might be replaced with some asynchronous service. class DummyDataService { static List<AccountData> getAccountDataList(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <AccountData>[ AccountData( name: localizations.rallyAccountDataChecking, primaryAmount: 2215.13, accountNumber: '1234561234', ), AccountData( name: localizations.rallyAccountDataHomeSavings, primaryAmount: 8678.88, accountNumber: '8888885678', ), AccountData( name: localizations.rallyAccountDataCarSavings, primaryAmount: 987.48, accountNumber: '8888889012', ), AccountData( name: localizations.rallyAccountDataVacation, primaryAmount: 253, accountNumber: '1231233456', ), ]; } static List<UserDetailData> getAccountDetailList(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <UserDetailData>[ UserDetailData( title: localizations.rallyAccountDetailDataAnnualPercentageYield, value: percentFormat(context).format(0.001), ), UserDetailData( title: localizations.rallyAccountDetailDataInterestRate, value: usdWithSignFormat(context).format(1676.14), ), UserDetailData( title: localizations.rallyAccountDetailDataInterestYtd, value: usdWithSignFormat(context).format(81.45), ), UserDetailData( title: localizations.rallyAccountDetailDataInterestPaidLastYear, value: usdWithSignFormat(context).format(987.12), ), UserDetailData( title: localizations.rallyAccountDetailDataNextStatement, value: shortDateFormat(context).format(DateTime.utc(2019, 12, 25)), ), UserDetailData( title: localizations.rallyAccountDetailDataAccountOwner, value: 'Philip Cao', ), ]; } static List<DetailedEventData> getDetailedEventItems() { // The following titles are not localized as they're product/brand names. return <DetailedEventData>[ DetailedEventData( title: 'Genoe', date: DateTime.utc(2019, 1, 24), amount: -16.54, ), DetailedEventData( title: 'Fortnightly Subscribe', date: DateTime.utc(2019, 1, 5), amount: -12.54, ), DetailedEventData( title: 'Circle Cash', date: DateTime.utc(2019, 1, 5), amount: 365.65, ), DetailedEventData( title: 'Crane Hospitality', date: DateTime.utc(2019, 1, 4), amount: -705.13, ), DetailedEventData( title: 'ABC Payroll', date: DateTime.utc(2018, 12, 15), amount: 1141.43, ), DetailedEventData( title: 'Shrine', date: DateTime.utc(2018, 12, 15), amount: -88.88, ), DetailedEventData( title: 'Foodmates', date: DateTime.utc(2018, 12, 4), amount: -11.69, ), ]; } static List<BillData> getBillDataList(BuildContext context) { // The following names are not localized as they're product/brand names. return <BillData>[ BillData( name: 'RedPay Credit', primaryAmount: 45.36, dueDate: dateFormatAbbreviatedMonthDay(context) .format(DateTime.utc(2019, 1, 29)), ), BillData( name: 'Rent', primaryAmount: 1200, dueDate: dateFormatAbbreviatedMonthDay(context) .format(DateTime.utc(2019, 2, 9)), isPaid: true, ), BillData( name: 'TabFine Credit', primaryAmount: 87.33, dueDate: dateFormatAbbreviatedMonthDay(context) .format(DateTime.utc(2019, 2, 22)), ), BillData( name: 'ABC Loans', primaryAmount: 400, dueDate: dateFormatAbbreviatedMonthDay(context) .format(DateTime.utc(2019, 2, 29)), ), ]; } static List<UserDetailData> getBillDetailList(BuildContext context, {required double dueTotal, required double paidTotal}) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <UserDetailData>[ UserDetailData( title: localizations.rallyBillDetailTotalAmount, value: usdWithSignFormat(context).format(paidTotal + dueTotal), ), UserDetailData( title: localizations.rallyBillDetailAmountPaid, value: usdWithSignFormat(context).format(paidTotal), ), UserDetailData( title: localizations.rallyBillDetailAmountDue, value: usdWithSignFormat(context).format(dueTotal), ), ]; } static List<BudgetData> getBudgetDataList(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <BudgetData>[ BudgetData( name: localizations.rallyBudgetCategoryCoffeeShops, primaryAmount: 70, amountUsed: 45.49, ), BudgetData( name: localizations.rallyBudgetCategoryGroceries, primaryAmount: 170, amountUsed: 16.45, ), BudgetData( name: localizations.rallyBudgetCategoryRestaurants, primaryAmount: 170, amountUsed: 123.25, ), BudgetData( name: localizations.rallyBudgetCategoryClothing, primaryAmount: 70, amountUsed: 19.45, ), ]; } static List<UserDetailData> getBudgetDetailList(BuildContext context, {required double capTotal, required double usedTotal}) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <UserDetailData>[ UserDetailData( title: localizations.rallyBudgetDetailTotalCap, value: usdWithSignFormat(context).format(capTotal), ), UserDetailData( title: localizations.rallyBudgetDetailAmountUsed, value: usdWithSignFormat(context).format(usedTotal), ), UserDetailData( title: localizations.rallyBudgetDetailAmountLeft, value: usdWithSignFormat(context).format(capTotal - usedTotal), ), ]; } static List<String> getSettingsTitles(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <String>[ localizations.rallySettingsManageAccounts, localizations.rallySettingsTaxDocuments, localizations.rallySettingsPasscodeAndTouchId, localizations.rallySettingsNotifications, localizations.rallySettingsPersonalInformation, localizations.rallySettingsPaperlessSettings, localizations.rallySettingsFindAtms, localizations.rallySettingsHelp, localizations.rallySettingsSignOut, ]; } static List<AlertData> getAlerts(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <AlertData>[ AlertData( message: localizations.rallyAlertsMessageHeadsUpShopping( percentFormat(context, decimalDigits: 0).format(0.9)), iconData: Icons.sort, ), AlertData( message: localizations.rallyAlertsMessageSpentOnRestaurants( usdWithSignFormat(context, decimalDigits: 0).format(120)), iconData: Icons.sort, ), AlertData( message: localizations.rallyAlertsMessageATMFees( usdWithSignFormat(context, decimalDigits: 0).format(24)), iconData: Icons.credit_card, ), AlertData( message: localizations.rallyAlertsMessageCheckingAccount( percentFormat(context, decimalDigits: 0).format(0.04)), iconData: Icons.attach_money, ), AlertData( message: localizations.rallyAlertsMessageUnassignedTransactions(16), iconData: Icons.not_interested, ), ]; } }
flutter/dev/integration_tests/new_gallery/lib/studies/rally/data.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/data.dart", "repo_id": "flutter", "token_count": 4414 }
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'; import 'package:provider/provider.dart'; import 'model/email_model.dart'; import 'model/email_store.dart'; class ComposePage extends StatelessWidget { const ComposePage({super.key}); @override Widget build(BuildContext context) { const String senderEmail = '[email protected]'; String subject = ''; String? recipient = 'Recipient'; String recipientAvatar = 'reply/avatars/avatar_0.jpg'; final EmailStore emailStore = Provider.of<EmailStore>(context); if (emailStore.selectedEmailId >= 0) { final Email currentEmail = emailStore.currentEmail; subject = currentEmail.subject; recipient = currentEmail.sender; recipientAvatar = currentEmail.avatar; } return Scaffold( body: SafeArea( bottom: false, child: SizedBox( height: double.infinity, child: Material( color: Theme.of(context).cardColor, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ _SubjectRow( subject: subject, ), const _SectionDivider(), const _SenderAddressRow( senderEmail: senderEmail, ), const _SectionDivider(), _RecipientsRow( recipients: recipient, avatar: recipientAvatar, ), const _SectionDivider(), Padding( padding: const EdgeInsets.all(12), child: TextField( minLines: 6, maxLines: 20, decoration: const InputDecoration.collapsed( hintText: 'New Message...', ), style: Theme.of(context).textTheme.bodyMedium, ), ), ], ), ), ), ), ), ); } } class _SubjectRow extends StatefulWidget { const _SubjectRow({required this.subject}); final String subject; @override _SubjectRowState createState() => _SubjectRowState(); } class _SubjectRowState extends State<_SubjectRow> { TextEditingController? _subjectController; @override void initState() { super.initState(); _subjectController = TextEditingController(text: widget.subject); } @override void dispose() { _subjectController!.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final ColorScheme colorScheme = theme.colorScheme; return Padding( padding: const EdgeInsets.only(top: 8), child: Row( children: <Widget>[ IconButton( key: const ValueKey<String>('ReplyExit'), onPressed: () => Navigator.of(context).pop(), icon: Icon( Icons.close, color: colorScheme.onSurface, ), ), Expanded( child: TextField( controller: _subjectController, style: theme.textTheme.titleLarge, decoration: InputDecoration.collapsed( hintText: 'Subject', hintStyle: theme.textTheme.titleLarge!.copyWith( color: theme.colorScheme.primary.withOpacity(0.5), ), ), ), ), IconButton( onPressed: () => Navigator.of(context).pop(), icon: IconButton( icon: ImageIcon( const AssetImage( 'reply/icons/twotone_send.png', package: 'flutter_gallery_assets', ), color: colorScheme.onSurface, ), onPressed: () => Navigator.of(context).pop(), ), ), ], ), ); } } class _SenderAddressRow extends StatefulWidget { const _SenderAddressRow({required this.senderEmail}); final String senderEmail; @override __SenderAddressRowState createState() => __SenderAddressRowState(); } class __SenderAddressRowState extends State<_SenderAddressRow> { late String senderEmail; @override void initState() { super.initState(); senderEmail = widget.senderEmail; } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TextTheme textTheme = theme.textTheme; final List<String> accounts = <String>[ '[email protected]', '[email protected]', ]; return PopupMenuButton<String>( padding: EdgeInsets.zero, onSelected: (String email) { setState(() { senderEmail = email; }); }, itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[ PopupMenuItem<String>( value: accounts[0], child: Text( accounts[0], style: textTheme.bodyMedium, ), ), PopupMenuItem<String>( value: accounts[1], child: Text( accounts[1], style: textTheme.bodyMedium, ), ), ], child: Padding( padding: const EdgeInsets.only( left: 12, top: 16, right: 10, bottom: 10, ), child: Row( children: <Widget>[ Expanded( child: Text( senderEmail, style: textTheme.bodyMedium, ), ), Icon( Icons.arrow_drop_down, color: theme.colorScheme.onSurface, ), ], ), ), ); } } class _RecipientsRow extends StatelessWidget { const _RecipientsRow({ required this.recipients, required this.avatar, }); final String recipients; final String avatar; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 12), child: Row( children: <Widget>[ Expanded( child: Wrap( children: <Widget>[ Chip( backgroundColor: Theme.of(context).chipTheme.secondarySelectedColor, padding: EdgeInsets.zero, avatar: CircleAvatar( backgroundImage: AssetImage( avatar, package: 'flutter_gallery_assets', ), ), label: Text( recipients, ), ), ], ), ), InkResponse( customBorder: const CircleBorder(), onTap: () {}, radius: 24, child: const Icon(Icons.add_circle_outline), ), ], ), ); } } class _SectionDivider extends StatelessWidget { const _SectionDivider(); @override Widget build(BuildContext context) { return const Divider( thickness: 1.1, indent: 10, endIndent: 10, ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/reply/compose_page.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/compose_page.dart", "repo_id": "flutter", "token_count": 3758 }
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 'dart:math'; import 'package:flutter/material.dart'; import '../../data/gallery_options.dart'; import '../../gallery_localizations.dart'; import '../../layout/adaptive.dart'; import '../../layout/image_placeholder.dart'; import '../../layout/letter_spacing.dart'; import '../../layout/text_scale.dart'; import 'app.dart'; import 'theme.dart'; const double _horizontalPadding = 24.0; double desktopLoginScreenMainAreaWidth({required BuildContext context}) { return min( 360 * reducedTextScale(context), MediaQuery.of(context).size.width - 2 * _horizontalPadding, ); } class LoginPage extends StatelessWidget { const LoginPage({super.key}); @override Widget build(BuildContext context) { final bool isDesktop = isDisplayDesktop(context); return ApplyTextOptions( child: isDesktop ? LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) => Scaffold( body: SafeArea( child: Center( child: SizedBox( width: desktopLoginScreenMainAreaWidth(context: context), child: const Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ _ShrineLogo(), SizedBox(height: 40), _UsernameTextField(), SizedBox(height: 16), _PasswordTextField(), SizedBox(height: 24), _CancelAndNextButtons(), SizedBox(height: 62), ], ), ), ), ), ), ) : Scaffold( body: SafeArea( child: ListView( restorationId: 'login_list_view', physics: const ClampingScrollPhysics(), padding: const EdgeInsets.symmetric( horizontal: _horizontalPadding, ), children: const <Widget>[ SizedBox(height: 80), _ShrineLogo(), SizedBox(height: 120), _UsernameTextField(), SizedBox(height: 12), _PasswordTextField(), _CancelAndNextButtons(), ], ), ), ), ); } } class _ShrineLogo extends StatelessWidget { const _ShrineLogo(); @override Widget build(BuildContext context) { return ExcludeSemantics( child: Column( children: <Widget>[ const FadeInImagePlaceholder( image: AssetImage('packages/shrine_images/diamond.png'), placeholder: SizedBox( width: 34, height: 34, ), ), const SizedBox(height: 16), Text( 'SHRINE', style: Theme.of(context).textTheme.headlineSmall, ), ], ), ); } } class _UsernameTextField extends StatelessWidget { const _UsernameTextField(); @override Widget build(BuildContext context) { final ColorScheme colorScheme = Theme.of(context).colorScheme; return TextField( textInputAction: TextInputAction.next, restorationId: 'username_text_field', cursorColor: colorScheme.onSurface, decoration: InputDecoration( labelText: GalleryLocalizations.of(context)!.shrineLoginUsernameLabel, labelStyle: TextStyle( letterSpacing: letterSpacingOrNone(mediumLetterSpacing), ), ), ); } } class _PasswordTextField extends StatelessWidget { const _PasswordTextField(); @override Widget build(BuildContext context) { final ColorScheme colorScheme = Theme.of(context).colorScheme; return TextField( restorationId: 'password_text_field', cursorColor: colorScheme.onSurface, obscureText: true, decoration: InputDecoration( labelText: GalleryLocalizations.of(context)!.shrineLoginPasswordLabel, labelStyle: TextStyle( letterSpacing: letterSpacingOrNone(mediumLetterSpacing), ), ), ); } } class _CancelAndNextButtons extends StatelessWidget { const _CancelAndNextButtons(); @override Widget build(BuildContext context) { final ColorScheme colorScheme = Theme.of(context).colorScheme; final bool isDesktop = isDisplayDesktop(context); final EdgeInsets buttonTextPadding = isDesktop ? const EdgeInsets.symmetric(horizontal: 24, vertical: 16) : EdgeInsets.zero; return Padding( padding: isDesktop ? EdgeInsets.zero : const EdgeInsets.all(8), child: OverflowBar( spacing: isDesktop ? 0 : 8, alignment: MainAxisAlignment.end, children: <Widget>[ TextButton( style: TextButton.styleFrom( shape: const BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(7)), ), ), onPressed: () { // The login screen is immediately displayed on top of // the Shrine home screen using onGenerateRoute and so // rootNavigator must be set to true in order to get out // of Shrine completely. Navigator.of(context, rootNavigator: true).pop(); }, child: Padding( padding: buttonTextPadding, child: Text( GalleryLocalizations.of(context)!.shrineCancelButtonCaption, style: TextStyle(color: colorScheme.onSurface), ), ), ), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 8, shape: const BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(7)), ), ), onPressed: () { Navigator.of(context).restorablePushNamed(ShrineApp.homeRoute); }, child: Padding( padding: buttonTextPadding, child: Text( GalleryLocalizations.of(context)!.shrineNextButtonCaption, style: TextStyle( letterSpacing: letterSpacingOrNone(largeLetterSpacing)), ), ), ), ], ), ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/login.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/login.dart", "repo_id": "flutter", "token_count": 3245 }
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 'colors.dart'; const List<Offset> _vertices = <Offset>[ Offset(0, -14), Offset(-17, 14), Offset(17, 14), Offset(0, -14), Offset(0, -7.37), Offset(10.855, 10.48), Offset(-10.855, 10.48), Offset(0, -7.37), ]; class TriangleCategoryIndicator extends CustomPainter { const TriangleCategoryIndicator( this.triangleWidth, this.triangleHeight, ); final double triangleWidth; final double triangleHeight; @override void paint(Canvas canvas, Size size) { final Path myPath = Path() ..addPolygon( List<Offset>.from(_vertices.map<Offset>((Offset vertex) { return Offset(size.width, size.height) / 2 + Offset(vertex.dx * triangleWidth / 34, vertex.dy * triangleHeight / 28); })), true, ); final Paint myPaint = Paint()..color = shrinePink400; canvas.drawPath(myPath, myPaint); } @override bool shouldRepaint(TriangleCategoryIndicator oldDelegate) => false; @override bool shouldRebuildSemantics(TriangleCategoryIndicator oldDelegate) => false; }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/triangle_category_indicator.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/triangle_category_indicator.dart", "repo_id": "flutter", "token_count": 488 }
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 <Foundation/Foundation.h> #import "TestNavigationController.h" #import <Flutter/Flutter.h> @implementation TestNavigationController - (void) viewWillAppear:(BOOL)animated { [self setNavigationBarHidden:YES animated:NO]; [super viewWillAppear:animated]; } - (nullable UIViewController *)popViewControllerAnimated:(BOOL)animated { FlutterViewController* root = (FlutterViewController*)[self.viewControllers objectAtIndex:0]; FlutterBasicMessageChannel* messageChannel = [FlutterBasicMessageChannel messageChannelWithName:@"navigation-test" binaryMessenger:root codec:[FlutterStringCodec sharedInstance]]; [messageChannel sendMessage:@"ping"]; return root; } @end
flutter/dev/integration_tests/platform_interaction/ios/Runner/TestNavigationController.m/0
{ "file_path": "flutter/dev/integration_tests/platform_interaction/ios/Runner/TestNavigationController.m", "repo_id": "flutter", "token_count": 349 }
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/material.dart'; import 'package:flutter/rendering.dart'; void main() { print('called main'); runApp(const MaterialApp(home: Test())); } class Test extends SingleChildRenderObjectWidget { const Test({ super.key }); @override RenderTest createRenderObject(BuildContext context) => RenderTest(); } class RenderTest extends RenderProxyBox { RenderTest({ RenderBox? child }) : super(child); @override void debugPaintSize(PaintingContext context, Offset offset) { super.debugPaintSize(context, offset); print('called debugPaintSize'); } @override void paint(PaintingContext context, Offset offset) { print('called paint'); } @override void reassemble() { print('called reassemble'); super.reassemble(); } }
flutter/dev/integration_tests/ui/lib/commands.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/lib/commands.dart", "repo_id": "flutter", "token_count": 290 }
590
This is an Example
flutter/dev/integration_tests/web/web/example/0
{ "file_path": "flutter/dev/integration_tests/web/web/example", "repo_id": "flutter", "token_count": 4 }
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'; 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: 'Integration Test App For Platform Messages', home: MyHomePage(title: 'Integration Test App For Platform Messages'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final TextEditingController _controller = TextEditingController(text: 'Text1'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('Hello World', ), // Create a text form field since we can't test clipboard unless // html document has focus. TextFormField( key: const Key('input'), enabled: true, controller: _controller, //initialValue: 'Text1', decoration: const InputDecoration( labelText: 'Text Input Field:', ), ), ], ), ), ); } }
flutter/dev/integration_tests/web_e2e_tests/lib/platform_messages_main.dart/0
{ "file_path": "flutter/dev/integration_tests/web_e2e_tests/lib/platform_messages_main.dart", "repo_id": "flutter", "token_count": 672 }
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 'dart:async' show Completer; import 'dart:convert' show base64Decode; import 'dart:typed_data' show ByteData, Uint8List; import 'dart:ui' as ui; import 'package:flutter/material.dart'; /// A 100x100 png in Display P3 colorspace. const String _displayP3Logo = 'iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAABdWlDQ1BrQ0dDb2xv' 'clNwYWNlRGlzcGxheVAzAAAokXWQvUvDUBTFT6tS0DqIDh0cMolD1NIKdnFoKxRF' 'MFQFq1OafgltfCQpUnETVyn4H1jBWXCwiFRwcXAQRAcR3Zw6KbhoeN6XVNoi3sfl' '/Ticc7lcwBtQGSv2AijplpFMxKS11Lrke4OHnlOqZrKooiwK/v276/PR9d5PiFlN' 'u3YQ2U9cl84ul3aeAlN//V3Vn8maGv3f1EGNGRbgkYmVbYsJ3iUeMWgp4qrgvMvH' 'gtMunzuelWSc+JZY0gpqhrhJLKc79HwHl4plrbWD2N6f1VeXxRzqUcxhEyYYilBR' 'gQQF4X/8044/ji1yV2BQLo8CLMpESRETssTz0KFhEjJxCEHqkLhz634PrfvJbW3v' 'FZhtcM4v2tpCAzidoZPV29p4BBgaAG7qTDVUR+qh9uZywPsJMJgChu8os2HmwiF3' 'e38M6Hvh/GMM8B0CdpXzryPO7RqFn4Er/QcXKWq8UwZBywAAANplWElmTU0AKgAA' 'AAgABgESAAMAAAABAAEAAAEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgExAAIAAAAh' 'AAAAZgEyAAIAAAAUAAAAiIdpAAQAAAABAAAAnAAAAAAAAABIAAAAAQAAAEgAAAAB' 'QWRvYmUgUGhvdG9zaG9wIDI0LjEgKE1hY2ludG9zaCkAADIwMjM6MDI6MDggMTA6' 'MTY6NDQAAAOQBAACAAAAFAAAAMagAgAEAAAAAQAAAGSgAwAEAAAAAQAAAGQAAAAA' 'MjAyMzowMjowOCAxMDoxMzoyMgBgamvuAAAACXBIWXMAAAsTAAALEwEAmpwYAAAL' 'v2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJh' 'ZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRm' 'OlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRm' 'LXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0i' 'IgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3Rp' 'ZmYvMS4wLyIKICAgICAgICAgICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9k' 'Yy9lbGVtZW50cy8xLjEvIgogICAgICAgICAgICB4bWxuczp4bXA9Imh0dHA6Ly9u' 'cy5hZG9iZS5jb20veGFwLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOnhtcE1NPSJo' 'dHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIgogICAgICAgICAgICB4bWxu' 'czpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291' 'cmNlRXZlbnQjIgogICAgICAgICAgICB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFk' 'b2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIKICAgICAgICAgICAg' 'eG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8x' 'LjAvIj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+NzI8L3RpZmY6WVJlc29s' 'dXRpb24+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50' 'YXRpb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyPC90aWZmOlhSZXNv' 'bHV0aW9uPgogICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3BuZzwvZGM6Zm9ybWF0' 'PgogICAgICAgICA8eG1wOk1vZGlmeURhdGU+MjAyMy0wMi0wOFQxMDoxNjo0NC0w' 'ODowMDwveG1wOk1vZGlmeURhdGU+CiAgICAgICAgIDx4bXA6Q3JlYXRvclRvb2w+' 'QWRvYmUgUGhvdG9zaG9wIDI0LjEgKE1hY2ludG9zaCk8L3htcDpDcmVhdG9yVG9v' 'bD4KICAgICAgICAgPHhtcDpDcmVhdGVEYXRlPjIwMjMtMDItMDhUMTA6MTM6MjIt' 'MDg6MDA8L3htcDpDcmVhdGVEYXRlPgogICAgICAgICA8eG1wOk1ldGFkYXRhRGF0' 'ZT4yMDIzLTAyLTA4VDEwOjE2OjQ0LTA4OjAwPC94bXA6TWV0YWRhdGFEYXRlPgog' 'ICAgICAgICA8eG1wTU06SGlzdG9yeT4KICAgICAgICAgICAgPHJkZjpTZXE+CiAg' 'ICAgICAgICAgICAgIDxyZGY6bGkgcmRmOnBhcnNlVHlwZT0iUmVzb3VyY2UiPgog' 'ICAgICAgICAgICAgICAgICA8c3RFdnQ6c29mdHdhcmVBZ2VudD5BZG9iZSBQaG90' 'b3Nob3AgMjQuMSAoTWFjaW50b3NoKTwvc3RFdnQ6c29mdHdhcmVBZ2VudD4KICAg' 'ICAgICAgICAgICAgICAgPHN0RXZ0OmNoYW5nZWQ+Lzwvc3RFdnQ6Y2hhbmdlZD4K' 'ICAgICAgICAgICAgICAgICAgPHN0RXZ0OndoZW4+MjAyMy0wMi0wOFQxMDoxNjo0' 'NC0wODowMDwvc3RFdnQ6d2hlbj4KICAgICAgICAgICAgICAgICAgPHN0RXZ0Omlu' 'c3RhbmNlSUQ+eG1wLmlpZDo3ZmM3YjMyNC0xNDUyLTQ2ZGUtODI2MC0yNGRmMTlh' 'YjdkNTc8L3N0RXZ0Omluc3RhbmNlSUQ+CiAgICAgICAgICAgICAgICAgIDxzdEV2' 'dDphY3Rpb24+c2F2ZWQ8L3N0RXZ0OmFjdGlvbj4KICAgICAgICAgICAgICAgPC9y' 'ZGY6bGk+CiAgICAgICAgICAgICAgIDxyZGY6bGkgcmRmOnBhcnNlVHlwZT0iUmVz' 'b3VyY2UiPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6c29mdHdhcmVBZ2VudD5B' 'ZG9iZSBQaG90b3Nob3AgMjQuMSAoTWFjaW50b3NoKTwvc3RFdnQ6c29mdHdhcmVB' 'Z2VudD4KICAgICAgICAgICAgICAgICAgPHN0RXZ0OmNoYW5nZWQ+Lzwvc3RFdnQ6' 'Y2hhbmdlZD4KICAgICAgICAgICAgICAgICAgPHN0RXZ0OndoZW4+MjAyMy0wMi0w' 'OFQxMDoxNjo0NC0wODowMDwvc3RFdnQ6d2hlbj4KICAgICAgICAgICAgICAgICAg' 'PHN0RXZ0Omluc3RhbmNlSUQ+eG1wLmlpZDpmM2UxNjllMy1jZmZhLTRjZjUtYmQ1' 'OS02YzgzODljYjk1MDk8L3N0RXZ0Omluc3RhbmNlSUQ+CiAgICAgICAgICAgICAg' 'ICAgIDxzdEV2dDphY3Rpb24+c2F2ZWQ8L3N0RXZ0OmFjdGlvbj4KICAgICAgICAg' 'ICAgICAgPC9yZGY6bGk+CiAgICAgICAgICAgIDwvcmRmOlNlcT4KICAgICAgICAg' 'PC94bXBNTTpIaXN0b3J5PgogICAgICAgICA8eG1wTU06T3JpZ2luYWxEb2N1bWVu' 'dElEPnhtcC5kaWQ6Q0RBNDM3N0E4QUY3MTFFREE1NDdCQjYwRDI1MDkyNkQ8L3ht' 'cE1NOk9yaWdpbmFsRG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkRvY3VtZW50' 'SUQ+YWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjA2M2QwNTUwLTVlNjctMjA0Mi1iN2Vl' 'LTg4ZDE2ZDc5MDAyYTwveG1wTU06RG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1N' 'OkRlcml2ZWRGcm9tIHJkZjpwYXJzZVR5cGU9IlJlc291cmNlIj4KICAgICAgICAg' 'ICAgPHN0UmVmOmluc3RhbmNlSUQ+eG1wLmlpZDpDREE0Mzc3NzhBRjcxMUVEQTU0' 'N0JCNjBEMjUwOTI2RDwvc3RSZWY6aW5zdGFuY2VJRD4KICAgICAgICAgICAgPHN0' 'UmVmOmRvY3VtZW50SUQ+eG1wLmRpZDpDREE0Mzc3ODhBRjcxMUVEQTU0N0JCNjBE' 'MjUwOTI2RDwvc3RSZWY6ZG9jdW1lbnRJRD4KICAgICAgICAgPC94bXBNTTpEZXJp' 'dmVkRnJvbT4KICAgICAgICAgPHhtcE1NOkluc3RhbmNlSUQ+eG1wLmlpZDpmM2Ux' 'NjllMy1jZmZhLTRjZjUtYmQ1OS02YzgzODljYjk1MDk8L3htcE1NOkluc3RhbmNl' 'SUQ+CiAgICAgICAgIDxwaG90b3Nob3A6SUNDUHJvZmlsZT5EaXNwbGF5IFAzPC9w' 'aG90b3Nob3A6SUNDUHJvZmlsZT4KICAgICAgICAgPHBob3Rvc2hvcDpDb2xvck1v' 'ZGU+MzwvcGhvdG9zaG9wOkNvbG9yTW9kZT4KICAgICAgICAgPHBob3Rvc2hvcDpE' 'b2N1bWVudEFuY2VzdG9ycz4KICAgICAgICAgICAgPHJkZjpCYWc+CiAgICAgICAg' 'ICAgICAgIDxyZGY6bGk+eG1wLmRpZDpDREE0Mzc3QThBRjcxMUVEQTU0N0JCNjBE' 'MjUwOTI2RDwvcmRmOmxpPgogICAgICAgICAgICA8L3JkZjpCYWc+CiAgICAgICAg' 'IDwvcGhvdG9zaG9wOkRvY3VtZW50QW5jZXN0b3JzPgogICAgICA8L3JkZjpEZXNj' 'cmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4Ka44gfwAACRBJREFU' 'eAHtnMtyHDUUhtvjccItUClSBQtY5wHCBpOq7L1K+UWy4QH8CjwHWeQVsiBskmUW' 'WcMCqgzhGiBz4/9knUHTTHvssW496VNR1K1WS0fn05Fa6h7vLZpG/wapxQKjWhQZ' '9DizwACksp4wABmAVGaBytQZPGQAUpkFKlNn8JABSGUWqEydwUMqAzKuTJ8k6rAV' 'MVfYS1A6ZdOrY5W9s0AwFEaaKbxSiL0/RNlA3ld4R2EAIiN0SQjjT2Wy867826Qb' 'jHd1cywY6LFzc4gZH89IBYM68IzYMFTkbgHpO4ydAlICBnXGlp0YskrBiDl3GNje' 'AykBA+OlgEG5vQZSCgaGSyW9BVICBnWmll4CKQUj1TAVQu4dkBIwMFgOGNTTKyAl' 'YOQYpgBh0hsgpWDk8oxeAXlTYABlT43N7ZXWGS4V93Vv6lKNVOaqhyzrKTlhWJ2X' 'NWSs/NUCwTCM37lh5J4z2iCrfEF1HgwMputkgdVc5wtOEH+NiI62rwOG5LVCensL' 'nRtLS3VAMBSGCT0D63rDTv2lg+tNM77m8ypaCvleK/xz9kKPQ+y+0s42DKtT+YpL' 'VZO6GSaEITgkkzR6TwE4E4W/mualLnyv6z8o/l1JgLyh448Vf/J209w8UBpv9v44' 'i9xLPl3fCz1D564DKKpCqgFihjEYss5Chp0q/eB9ndDV/26aZ4oeKf2xwgsBOlWM' 'oZei/CMBuKX4tsI9Xbj/VtPcwZt+VRCMid70jXWfG84U1yVSmjG4aJBFXf0ajxa/' 'Kfwij5DxXpMu43L+tdLvdllO+mPcTttyL2XIq6ydr5V/Vrrd6+p3E+S6C7nS2jAE' 'YqrgDKf4yU9Nc2ggpBOGHyvsK4z8uYPROuYaeci7BKWh7lDnTxQMDB5ox1XERYG0' 'YagXT/AIGW4hGCcG4qmGLRmOKWEr4d7wfh2fKBiASXBsacXiYkDWwdD3UwvNzoRj' 's7yMpQeqOBKWpePjAEQ1UIoAacNgmMIzgKHjI8z/vGmuyWA8EEUVylRgjqftRwrm' 'DVUMX9mBtGH4CdwNU+YZZrCoJFqFWR2KQ08pPtFnBRLCkCfgDXMFnniWcwae0bJd' 'stMAygk6KKDL3B+b52SNeULRv/RCJTzu2DqDcy3yJlpLHMgzvv3AP00pnS0PsiWX' 'sC4dP1GFnyuw7tz6AeKqSrPwTS4Yvw1D5/S8Az6E1vrjS5TQ+fVcMKiPuqiTY4nT' 'QTEwULmIJAdCy9owfKUzVuCC8fBD9U4ebZVPW1B5hTqlI3XjIQ997Vk8dF1LkwJZ' 'BwM4vvuN2A6RAl+h2B3+Ky9OF6mR1C7nNTPZHNIFwysz1dwx1qPuM80dnynvnkB5' 'Tuepm+6a6aBYzur6h5x3dZc4Xe3/lZykJ2BZPCGcwDk30fHMV/zIp0Vfb1hdl4hN' 'B9OpyLAVHcgmGDKQm8x5lBGYx95g3FZaTAfTqcjkHhXIBWBg9JkWGiPeZwjIC0/B' 'jFESiunwQuull1JkpHim4Pb3u2LciGuxZOVN2lULlYE7h6mg7DnPmfKQ7zSPnPp0' 'M0aQLfuh6XCqX16h203FztZ2IdSItnKRcY7fGMaSqB7SNWe0lOXFEzP4j4pjdq5W' 'NdudopPXDR0ZXtcKimM8YMQ0YrSyLghj2Tg1VAt0BwY+VYh0crqYbl1KAQnPkBdF' 'hUF90YDQkmiFoVmlYjBS/OCTJkezIQWhJD0HpTeJAN4gj+KLZN9UXJTrpovp1i60' 'DSOF4tGAoLwa4sbUDVBYjJL3I8VR60eHqwo6ed0oiiY5QWfaFXrG8uJZlij/RzUI' 'Sl/AU0ZsWCnvp1qp3/KtSNG2yxrI6YBO6OY31Zx9DEbMv9jQpVxUILQI5YnPGb72' 'tYc157sp5b3tFasGCDqhGzpKN94uLj0jqrF8w9tR9DouAIV9q4lfBt/zCtUE5B66' 'oaNg/O+jurYBY59HB4KCm6Cooft+AXLfN6jIvlHLmE4H6XZfAffYD+cM0nL0miRA' 'aOgGKOz0zvmikI/YlNftb3FfCZGxeR/CR3p3NU+g01wwxuGckQMGbU8GhMK7oPjG' 'zXl5rp74gLwlhe9TvTxguBKMOXMgxsEzckqy9yFhI8zdibU/5Pa76JE632NfSxtq' 'X8gQfFHIK9ysbw2tTnnFoer+Br0Fg+0dezwnKZ9IIQyTPMgTXB3E2jNZaDuV2H1x' 'ovp5fepExwzdWSSsS58juU9MpZ/TyfTNYZuwDlwyOQyrwxqp2XMhT1nonI08g3IC' 'BZ0zkmWR574udY4TdPQwin4GlBWIgWnF4cdpx5DIAcXqEIxjOghBaaEu2TpqaI8a' 'gNDw8DPOI4Oi9OjDF2WaZ/ysT0nxVG+QUAdLyx7XAoSGhx88O0/xYOy7KU6vJKpj' 'WRaeEcAI684OwXcIV29NQFag6I3iiVn/qdYJUpon0q2EeynDbmbO8EPUSp2hYUod' '1wYEA031/Y3rLfruN+oPdni0tacpD6SKYSqEXx0QDCUQMxku+k/atDvgQPunqeIT' 'eAjCjrMsDG2ouEgsY7k/fAwYrZTpwdF+9CkPYfU90ZbIWHGZhd8GI1QHBH0FYWVF' 'r1PxifezaK3CV14PcF6LVAcEGBgohBLsKU11jaGGPxwwYgXZNib38c2w9l/4Kw88' 'PfHovPK5E3m4L3xn0y5Hl4tIdUCwghksGL6Whsdwuk4WvOZKf1qjRihVApGhl4Ll' 'tV6wDclleowDA1+TpzAaVCvrDBZTWe9tyYBvo2vVQGxcbw8t2zS06542FPLREUpJ' '1UDMKCU8pRSUXgAp4SnmOdYpcsW9AGLGKOEpVneuuFdASngKIHIOX70CYr20hKfk' 'gtJLIDa+E4drCAMWI7Y6wjVQDii9BILBzWC5ocSAfV4ZvQVSCgr1pvSUXgMpBcW8' 'k/pjS++BYBAzUO7hK4Wn7AQQg2Jxnyf6nQECDIRem8NT+CtG7P9TV0ypfvt9m8Ya' 'FGJ7bN2mnK571g2RXXkvm76TQEIjAIXezMuuWL05BE6Z/Gwh1lCz80BkKycYMaXE' 'gr3yrjmlwqXLjmWw1O2I5Wmp9Xxjyh+AVIZ6ADIAqcwClakzeMgApDILVKbO4CED' 'kMosUJk6g4dUBuRfvf1am9VRqzYAAAAASUVORK5CYII='; void main() => run(Setup.drawnImage); enum Setup { none, image, canvasSaveLayer, blur, drawnImage, } void run(Setup setup) { runApp(MyApp(setup)); } class MyApp extends StatelessWidget { const MyApp(this._setup, {super.key}); final Setup _setup; @override Widget build(BuildContext context) { return MaterialApp( title: 'Wide Gamut Test', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(_setup, title: 'Wide Gamut Test'), ); } } class _SaveLayerDrawer extends CustomPainter { _SaveLayerDrawer(this._image); final ui.Image? _image; @override void paint(Canvas canvas, Size size) { if (_image != null) { final Rect imageRect = Rect.fromCenter( center: Offset.zero, width: _image!.width.toDouble(), height: _image!.height.toDouble()); canvas.saveLayer(imageRect, Paint()); canvas.drawRect( imageRect.inflate(-_image!.width.toDouble() / 4.0), Paint() ..style = PaintingStyle.stroke ..color = const Color(0xffffffff) ..strokeWidth = 3); canvas.saveLayer(imageRect, Paint()..blendMode = BlendMode.dstOver); canvas.drawImage(_image!, Offset(-_image!.width / 2.0, -_image!.height / 2.0), Paint()); canvas.restore(); canvas.restore(); } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => true; } Future<ui.Image> _drawImage() async { final ui.PictureRecorder recorder = ui.PictureRecorder(); const Size markerSize = Size(120, 120); final double canvasSize = markerSize.height + 3; final Canvas canvas = Canvas( recorder, Rect.fromLTWH(0, 0, canvasSize, canvasSize), ); final Paint ovalPaint = Paint()..color = const Color(0xff00ff00); final Path ovalPath = Path() ..addOval(Rect.fromLTWH( (canvasSize - markerSize.width) / 2, 1, markerSize.width, markerSize.height, )); canvas.drawPath(ovalPath, ovalPaint); final ui.Picture picture = recorder.endRecording(); final ui.Image image = await picture.toImage( canvasSize.toInt(), (canvasSize + 0).toInt(), ); final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.rawExtendedRgba128); final Completer<ui.Image> completer = Completer<ui.Image>(); ui.decodeImageFromPixels(Uint8List.view(byteData!.buffer), canvasSize.toInt(), canvasSize.toInt(), ui.PixelFormat.rgbaFloat32, (ui.Image image) { completer.complete(image); }); return completer.future; } Future<ui.Image> _loadImage() async { final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromUint8List(base64Decode(_displayP3Logo)); final ui.ImageDescriptor descriptor = await ui.ImageDescriptor.encoded(buffer); final ui.Codec codec = await descriptor.instantiateCodec(); return (await codec.getNextFrame()).image; } class MyHomePage extends StatefulWidget { const MyHomePage(this.setup, {super.key, required this.title}); final Setup setup; final String title; @override State<StatefulWidget> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { ui.Image? _image; @override void initState() { switch (widget.setup) { case Setup.canvasSaveLayer: _loadImage().then((ui.Image? value) => setState(() { _image = value; })); case Setup.drawnImage: _drawImage().then((ui.Image? value) => setState(() { _image = value; })); case Setup.image || Setup.blur || Setup.none: break; } super.initState(); } @override Widget build(BuildContext context) { late Widget imageWidget; switch (widget.setup) { case Setup.none: imageWidget = Container(); case Setup.image: imageWidget = Image.memory(base64Decode(_displayP3Logo)); case Setup.drawnImage: imageWidget = CustomPaint(painter: _SaveLayerDrawer(_image)); case Setup.canvasSaveLayer: imageWidget = CustomPaint(painter: _SaveLayerDrawer(_image)); case Setup.blur: imageWidget = Stack( children: <Widget>[ const ColoredBox( color: Color(0xff00ff00), child: SizedBox( width: 100, height: 100, ), ), ImageFiltered( imageFilter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6), child: Image.memory(base64Decode(_displayP3Logo))), ], ); } return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ imageWidget, ], ), ), ); } }
flutter/dev/integration_tests/wide_gamut_test/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/wide_gamut_test/lib/main.dart", "repo_id": "flutter", "token_count": 8903 }
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/foundation.dart'; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); enum LerpTarget { circle, roundedRect, rect, stadium, polygon, star, } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { static final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final OptionModel _model = OptionModel(); final TextEditingController textController = TextEditingController(); @override void initState() { super.initState(); _model.addListener(_modelChanged); } @override void dispose() { super.dispose(); _model.removeListener(_modelChanged); } void _modelChanged() { setState(() {}); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( key: scaffoldKey, appBar: AppBar( title: const Text('Star Border'), backgroundColor: const Color(0xff323232), ), body: Column( children: <Widget>[ ColoredBox(color: Colors.grey.shade200, child: Options(_model)), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( alignment: Alignment.center, width: 300, height: 200, decoration: ShapeDecoration( color: Colors.blue.shade100, shape: lerpBorder( StarBorder.polygon( side: const BorderSide(strokeAlign: BorderSide.strokeAlignCenter, width: 2), sides: _model.points, pointRounding: _model.pointRounding, rotation: _model.rotation, squash: _model.squash, ), _model._lerpTarget, _model._lerpAmount, to: _model.lerpTo, )!, ), child: const Text('Polygon'), ), Container( alignment: Alignment.center, width: 300, height: 200, decoration: ShapeDecoration( color: Colors.blue.shade100, shape: lerpBorder( StarBorder( side: const BorderSide(strokeAlign: BorderSide.strokeAlignCenter, width: 2), points: _model.points, innerRadiusRatio: _model.innerRadiusRatio, pointRounding: _model.pointRounding, valleyRounding: _model.valleyRounding, rotation: _model.rotation, squash: _model.squash, ), _model._lerpTarget, _model._lerpAmount, to: _model.lerpTo, )!, ), child: const Text('Star'), ), ], ), ), ], ), ), ); } } class OptionModel extends ChangeNotifier { double get pointRounding => _pointRounding; double _pointRounding = 0.0; set pointRounding(double value) { if (value != _pointRounding) { _pointRounding = value; if (_valleyRounding + _pointRounding > 1) { _valleyRounding = 1.0 - _pointRounding; } notifyListeners(); } } double get valleyRounding => _valleyRounding; double _valleyRounding = 0.0; set valleyRounding(double value) { if (value != _valleyRounding) { _valleyRounding = value; if (_valleyRounding + _pointRounding > 1) { _pointRounding = 1.0 - _valleyRounding; } notifyListeners(); } } double get squash => _squash; double _squash = 0.0; set squash(double value) { if (value != _squash) { _squash = value; notifyListeners(); } } double get rotation => _rotation; double _rotation = 0.0; set rotation(double value) { if (value != _rotation) { _rotation = value; notifyListeners(); } } double get innerRadiusRatio => _innerRadiusRatio; double _innerRadiusRatio = 0.4; set innerRadiusRatio(double value) { if (value != _innerRadiusRatio) { _innerRadiusRatio = clampDouble(value, 0.0001, double.infinity); notifyListeners(); } } double get points => _points; double _points = 5; set points(double value) { if (value != _points) { _points = value; notifyListeners(); } } double get lerpAmount => _lerpAmount; double _lerpAmount = 0.0; set lerpAmount(double value) { if (value != _lerpAmount) { _lerpAmount = value; notifyListeners(); } } bool get lerpTo => _lerpTo; bool _lerpTo = true; set lerpTo(bool value) { if (_lerpTo != value) { _lerpTo = value; notifyListeners(); } } LerpTarget get lerpTarget => _lerpTarget; LerpTarget _lerpTarget = LerpTarget.circle; set lerpTarget(LerpTarget value) { if (value != _lerpTarget) { _lerpTarget = value; notifyListeners(); } } void reset() { final OptionModel defaultModel = OptionModel(); _pointRounding = defaultModel.pointRounding; _valleyRounding = defaultModel.valleyRounding; _rotation = defaultModel.rotation; _squash = defaultModel.squash; _lerpAmount = defaultModel.lerpAmount; _lerpTo = defaultModel.lerpTo; _lerpTarget = defaultModel.lerpTarget; _innerRadiusRatio = defaultModel._innerRadiusRatio; _points = defaultModel.points; notifyListeners(); } } class Options extends StatefulWidget { const Options(this.model, {super.key}); final OptionModel model; @override State<Options> createState() => _OptionsState(); } class _OptionsState extends State<Options> { @override void initState() { super.initState(); widget.model.addListener(_modelChanged); } @override void didUpdateWidget(Options oldWidget) { super.didUpdateWidget(oldWidget); if (widget.model != oldWidget.model) { oldWidget.model.removeListener(_modelChanged); widget.model.addListener(_modelChanged); } } @override void dispose() { super.dispose(); widget.model.removeListener(_modelChanged); } void _modelChanged() { setState(() {}); } double sliderValue = 0.0; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 10.0), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Row( children: <Widget>[ Expanded( child: ControlSlider( label: 'Point Rounding', value: widget.model.pointRounding, onChanged: (double value) { widget.model.pointRounding = value; }, ), ), Expanded( child: ControlSlider( label: 'Valley Rounding', value: widget.model.valleyRounding, onChanged: (double value) { widget.model.valleyRounding = value; }, ), ), ], ), Row( children: <Widget>[ Expanded( child: ControlSlider( label: 'Squash', value: widget.model.squash, onChanged: (double value) { widget.model.squash = value; }, ), ), Expanded( child: ControlSlider( label: 'Rotation', value: widget.model.rotation, max: 360, onChanged: (double value) { widget.model.rotation = value; }, ), ), ], ), Row( children: <Widget>[ Expanded( child: Row( children: <Widget>[ Expanded( child: ControlSlider( label: 'Points', value: widget.model.points, min: 2, max: 20, onChanged: (double value) { widget.model.points = value; }, ), ), OutlinedButton( child: const Text('Nearest'), onPressed: () { widget.model.points = widget.model.points.roundToDouble(); }), ], ), ), Expanded( child: ControlSlider( label: 'Inner Radius', value: widget.model.innerRadiusRatio, onChanged: (double value) { widget.model.innerRadiusRatio = value; }, ), ), ], ), Row( children: <Widget>[ Expanded( flex: 2, child: Padding( padding: const EdgeInsetsDirectional.only(end: 8.0), child: ControlSlider( label: 'Lerp', value: widget.model.lerpAmount, onChanged: (double value) { widget.model.lerpAmount = value; }, ), ), ), Padding( padding: const EdgeInsetsDirectional.only(start: 8.0, end: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row(children: <Widget>[ Radio<bool>( value: true, groupValue: widget.model.lerpTo, onChanged: (bool? value) { widget.model.lerpTo = value!; }), const Text('To'), ]), Row(children: <Widget>[ Radio<bool>( value: false, groupValue: widget.model.lerpTo, onChanged: (bool? value) { widget.model.lerpTo = value!; }), const Text('From'), ]) ], ), ), Expanded( child: Row( children: <Widget>[ Expanded( child: DropdownButton<LerpTarget>( items: LerpTarget.values.map<DropdownMenuItem<LerpTarget>>((LerpTarget target) { return DropdownMenuItem<LerpTarget>(value: target, child: Text(target.name)); }).toList(), value: widget.model.lerpTarget, onChanged: (LerpTarget? value) { if (value == null) { return; } widget.model.lerpTarget = value; }, ), ), ], ), ), ], ), ElevatedButton( onPressed: () { widget.model.reset(); sliderValue = 0.0; }, child: const Text('Reset'), ), ], ), ); } } class ControlSlider extends StatelessWidget { const ControlSlider({ super.key, required this.label, required this.value, required this.onChanged, this.min = 0.0, this.max = 1.0, }); final String label; final double value; final void Function(double value) onChanged; final double min; final double max; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(4.0), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(label), Expanded( child: Slider( label: value.toStringAsFixed(1), onChanged: onChanged, min: min, max: max, value: value, ), ), Text( value.toStringAsFixed(3), ), ], ), ); } } const Color lerpToColor = Colors.red; const BorderSide lerpToBorder = BorderSide(width: 5, color: lerpToColor); ShapeBorder? lerpBorder(StarBorder border, LerpTarget target, double t, {bool to = true}) { switch (target) { case LerpTarget.circle: if (to) { return border.lerpTo(const CircleBorder(side: lerpToBorder, eccentricity: 0.5), t); } else { return border.lerpFrom(const CircleBorder(side: lerpToBorder, eccentricity: 0.5), t); } case LerpTarget.roundedRect: if (to) { return border.lerpTo( const RoundedRectangleBorder( side: lerpToBorder, borderRadius: BorderRadius.all( Radius.circular(10), ), ), t, ); } else { return border.lerpFrom( const RoundedRectangleBorder( side: lerpToBorder, borderRadius: BorderRadius.all( Radius.circular(10), ), ), t, ); } case LerpTarget.rect: if (to) { return border.lerpTo(const RoundedRectangleBorder(side: lerpToBorder), t); } else { return border.lerpFrom(const RoundedRectangleBorder(side: lerpToBorder), t); } case LerpTarget.stadium: if (to) { return border.lerpTo(const StadiumBorder(side: lerpToBorder), t); } else { return border.lerpFrom(const StadiumBorder(side: lerpToBorder), t); } case LerpTarget.polygon: if (to) { return border.lerpTo(const StarBorder.polygon(side: lerpToBorder, sides: 4), t); } else { return border.lerpFrom(const StarBorder.polygon(side: lerpToBorder, sides: 4), t); } case LerpTarget.star: if (to) { return border.lerpTo(const StarBorder(side: lerpToBorder, innerRadiusRatio: .5), t); } else { return border.lerpFrom(const StarBorder(side: lerpToBorder, innerRadiusRatio: .5), t); } } }
flutter/dev/manual_tests/lib/star_border.dart/0
{ "file_path": "flutter/dev/manual_tests/lib/star_border.dart", "repo_id": "flutter", "token_count": 8314 }
594
tags: # This tag tells the test framework to not shuffle the test order according to # the --test-randomize-ordering-seed for the suites that have this tag. no-shuffle: allow_test_randomization: false
flutter/dev/tools/gen_defaults/dart_test.yaml/0
{ "file_path": "flutter/dev/tools/gen_defaults/dart_test.yaml", "repo_id": "flutter", "token_count": 60 }
595
{ "version": "v0_206", "md.comp.input-chip.container.elevation": "md.sys.elevation.level0", "md.comp.input-chip.container.height": 32.0, "md.comp.input-chip.container.shape": "md.sys.shape.corner.small", "md.comp.input-chip.disabled.label-text.color": "onSurface", "md.comp.input-chip.disabled.label-text.opacity": 0.38, "md.comp.input-chip.disabled.selected.container.color": "onSurface", "md.comp.input-chip.disabled.selected.container.opacity": 0.12, "md.comp.input-chip.disabled.unselected.outline.color": "onSurface", "md.comp.input-chip.disabled.unselected.outline.opacity": 0.12, "md.comp.input-chip.dragged.container.elevation": "md.sys.elevation.level4", "md.comp.input-chip.focus.indicator.color": "secondary", "md.comp.input-chip.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.input-chip.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.input-chip.label-text.text-style": "labelLarge", "md.comp.input-chip.selected.container.color": "secondaryContainer", "md.comp.input-chip.selected.dragged.label-text.color": "onSecondaryContainer", "md.comp.input-chip.selected.dragged.state-layer.color": "onSecondaryContainer", "md.comp.input-chip.selected.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity", "md.comp.input-chip.selected.focus.label-text.color": "onSecondaryContainer", "md.comp.input-chip.selected.focus.state-layer.color": "onSecondaryContainer", "md.comp.input-chip.selected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.input-chip.selected.hover.label-text.color": "onSecondaryContainer", "md.comp.input-chip.selected.hover.state-layer.color": "onSecondaryContainer", "md.comp.input-chip.selected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.input-chip.selected.label-text.color": "onSecondaryContainer", "md.comp.input-chip.selected.outline.width": 0.0, "md.comp.input-chip.selected.pressed.label-text.color": "onSecondaryContainer", "md.comp.input-chip.selected.pressed.state-layer.color": "onSecondaryContainer", "md.comp.input-chip.selected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.input-chip.unselected.dragged.label-text.color": "onSurfaceVariant", "md.comp.input-chip.unselected.dragged.state-layer.color": "onSurfaceVariant", "md.comp.input-chip.unselected.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity", "md.comp.input-chip.unselected.focus.label-text.color": "onSurfaceVariant", "md.comp.input-chip.unselected.focus.outline.color": "onSurfaceVariant", "md.comp.input-chip.unselected.focus.state-layer.color": "onSurfaceVariant", "md.comp.input-chip.unselected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.input-chip.unselected.hover.label-text.color": "onSurfaceVariant", "md.comp.input-chip.unselected.hover.state-layer.color": "onSurfaceVariant", "md.comp.input-chip.unselected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.input-chip.unselected.label-text.color": "onSurfaceVariant", "md.comp.input-chip.unselected.outline.color": "outline", "md.comp.input-chip.unselected.outline.width": 1.0, "md.comp.input-chip.unselected.pressed.label-text.color": "onSurfaceVariant", "md.comp.input-chip.unselected.pressed.state-layer.color": "onSurfaceVariant", "md.comp.input-chip.unselected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.input-chip.with-avatar.avatar.shape": "md.sys.shape.corner.full", "md.comp.input-chip.with-avatar.avatar.size": 24.0, "md.comp.input-chip.with-avatar.disabled.avatar.opacity": 0.38, "md.comp.input-chip.with-leading-icon.disabled.leading-icon.color": "onSurface", "md.comp.input-chip.with-leading-icon.disabled.leading-icon.opacity": 0.38, "md.comp.input-chip.with-leading-icon.leading-icon.size": 18.0, "md.comp.input-chip.with-leading-icon.selected.dragged.leading-icon.color": "onSecondaryContainer", "md.comp.input-chip.with-leading-icon.selected.focus.leading-icon.color": "primary", "md.comp.input-chip.with-leading-icon.selected.hover.leading-icon.color": "primary", "md.comp.input-chip.with-leading-icon.selected.leading-icon.color": "primary", "md.comp.input-chip.with-leading-icon.selected.pressed.leading-icon.color": "primary", "md.comp.input-chip.with-leading-icon.unselected.dragged.leading-icon.color": "onSurfaceVariant", "md.comp.input-chip.with-leading-icon.unselected.focus.leading-icon.color": "primary", "md.comp.input-chip.with-leading-icon.unselected.hover.leading-icon.color": "primary", "md.comp.input-chip.with-leading-icon.unselected.leading-icon.color": "onSurfaceVariant", "md.comp.input-chip.with-leading-icon.unselected.pressed.leading-icon.color": "primary", "md.comp.input-chip.with-trailing-icon.disabled.trailing-icon.color": "onSurface", "md.comp.input-chip.with-trailing-icon.disabled.trailing-icon.opacity": 0.38, "md.comp.input-chip.with-trailing-icon.selected.dragged.trailing-icon.color": "primary", "md.comp.input-chip.with-trailing-icon.selected.focus.trailing-icon.color": "onSecondaryContainer", "md.comp.input-chip.with-trailing-icon.selected.hover.trailing-icon.color": "onSecondaryContainer", "md.comp.input-chip.with-trailing-icon.selected.pressed.trailing-icon.color": "onSecondaryContainer", "md.comp.input-chip.with-trailing-icon.selected.trailing-icon.color": "onSecondaryContainer", "md.comp.input-chip.with-trailing-icon.trailing-icon.size": 18.0, "md.comp.input-chip.with-trailing-icon.unselected.dragged.trailing-icon.color": "primary", "md.comp.input-chip.with-trailing-icon.unselected.focus.trailing-icon.color": "onSurfaceVariant", "md.comp.input-chip.with-trailing-icon.unselected.hover.trailing-icon.color": "onSurfaceVariant", "md.comp.input-chip.with-trailing-icon.unselected.pressed.trailing-icon.color": "onSurfaceVariant", "md.comp.input-chip.with-trailing-icon.unselected.trailing-icon.color": "onSurfaceVariant" }
flutter/dev/tools/gen_defaults/data/chip_input.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/chip_input.json", "repo_id": "flutter", "token_count": 2251 }
596
{ "version": "v0_206", "md.comp.filled-icon-button.container.color": "primary", "md.comp.filled-icon-button.container.height": 40.0, "md.comp.filled-icon-button.container.shape": "md.sys.shape.corner.full", "md.comp.filled-icon-button.container.width": 40.0, "md.comp.filled-icon-button.disabled.container.color": "onSurface", "md.comp.filled-icon-button.disabled.container.opacity": 0.12, "md.comp.filled-icon-button.disabled.icon.color": "onSurface", "md.comp.filled-icon-button.disabled.icon.opacity": 0.38, "md.comp.filled-icon-button.focus.icon.color": "onPrimary", "md.comp.filled-icon-button.focus.indicator.color": "secondary", "md.comp.filled-icon-button.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.filled-icon-button.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.filled-icon-button.focus.state-layer.color": "onPrimary", "md.comp.filled-icon-button.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.filled-icon-button.hover.icon.color": "onPrimary", "md.comp.filled-icon-button.hover.state-layer.color": "onPrimary", "md.comp.filled-icon-button.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.filled-icon-button.icon.color": "onPrimary", "md.comp.filled-icon-button.icon.size": 24.0, "md.comp.filled-icon-button.pressed.icon.color": "onPrimary", "md.comp.filled-icon-button.pressed.state-layer.color": "onPrimary", "md.comp.filled-icon-button.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.filled-icon-button.selected.container.color": "primary", "md.comp.filled-icon-button.toggle.selected.focus.icon.color": "onPrimary", "md.comp.filled-icon-button.toggle.selected.focus.state-layer.color": "onPrimary", "md.comp.filled-icon-button.toggle.selected.hover.icon.color": "onPrimary", "md.comp.filled-icon-button.toggle.selected.hover.state-layer.color": "onPrimary", "md.comp.filled-icon-button.toggle.selected.icon.color": "onPrimary", "md.comp.filled-icon-button.toggle.selected.pressed.icon.color": "onPrimary", "md.comp.filled-icon-button.toggle.selected.pressed.state-layer.color": "onPrimary", "md.comp.filled-icon-button.toggle.unselected.focus.icon.color": "primary", "md.comp.filled-icon-button.toggle.unselected.focus.state-layer.color": "primary", "md.comp.filled-icon-button.toggle.unselected.hover.icon.color": "primary", "md.comp.filled-icon-button.toggle.unselected.hover.state-layer.color": "primary", "md.comp.filled-icon-button.toggle.unselected.icon.color": "primary", "md.comp.filled-icon-button.toggle.unselected.pressed.icon.color": "primary", "md.comp.filled-icon-button.toggle.unselected.pressed.state-layer.color": "primary", "md.comp.filled-icon-button.unselected.container.color": "surfaceContainerHighest" }
flutter/dev/tools/gen_defaults/data/icon_button_filled.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/icon_button_filled.json", "repo_id": "flutter", "token_count": 1036 }
597
{ "version": "v0_206", "md.comp.search-view.container.color": "surfaceContainerHigh", "md.comp.search-view.container.elevation": "md.sys.elevation.level3", "md.comp.search-view.divider.color": "outline", "md.comp.search-view.docked.container.shape": "md.sys.shape.corner.extra-large", "md.comp.search-view.docked.header.container.height": 56.0, "md.comp.search-view.full-screen.container.shape": "md.sys.shape.corner.none", "md.comp.search-view.full-screen.header.container.height": 72.0, "md.comp.search-view.header.input-text.color": "onSurface", "md.comp.search-view.header.input-text.text-style": "bodyLarge", "md.comp.search-view.header.leading-icon.color": "onSurface", "md.comp.search-view.header.supporting-text.color": "onSurfaceVariant", "md.comp.search-view.header.supporting-text.text-style": "bodyLarge", "md.comp.search-view.header.trailing-icon.color": "onSurfaceVariant" }
flutter/dev/tools/gen_defaults/data/search_view.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/search_view.json", "repo_id": "flutter", "token_count": 349 }
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 'template.dart'; class ExpansionTileTemplate extends TokenTemplate { const ExpansionTileTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', }); @override String generate() => ''' class _${blockName}DefaultsM3 extends ExpansionTileThemeData { _${blockName}DefaultsM3(this.context); final BuildContext context; late final ThemeData _theme = Theme.of(context); late final ColorScheme _colors = _theme.colorScheme; @override Color? get textColor => ${componentColor('md.comp.list.list-item.label-text')}; @override Color? get iconColor => ${componentColor('md.comp.list.list-item.selected.trailing-icon')}; @override Color? get collapsedTextColor => ${componentColor('md.comp.list.list-item.label-text')}; @override Color? get collapsedIconColor => ${componentColor('md.comp.list.list-item.trailing-icon')}; } '''; }
flutter/dev/tools/gen_defaults/lib/expansion_tile_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/expansion_tile_template.dart", "repo_id": "flutter", "token_count": 331 }
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 'template.dart'; class SearchViewTemplate extends TokenTemplate { const SearchViewTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', super.textThemePrefix = '_textTheme.' }); @override String generate() => ''' class _${blockName}DefaultsM3 extends ${blockName}ThemeData { _${blockName}DefaultsM3(this.context, {required this.isFullScreen}); final BuildContext context; final bool isFullScreen; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; static double fullScreenBarHeight = ${getToken('md.comp.search-view.full-screen.header.container.height')}; @override Color? get backgroundColor => ${componentColor('md.comp.search-view.container')}; @override double? get elevation => ${elevation('md.comp.search-view.container')}; @override Color? get surfaceTintColor => ${colorOrTransparent('md.comp.search-view.container.surface-tint-layer.color')}; // No default side @override OutlinedBorder? get shape => isFullScreen ? ${shape('md.comp.search-view.full-screen.container')} : ${shape('md.comp.search-view.docked.container')}; @override TextStyle? get headerTextStyle => ${textStyleWithColor('md.comp.search-view.header.input-text')}; @override TextStyle? get headerHintStyle => ${textStyleWithColor('md.comp.search-view.header.supporting-text')}; @override BoxConstraints get constraints => const BoxConstraints(minWidth: 360.0, minHeight: 240.0); @override Color? get dividerColor => ${componentColor('md.comp.search-view.divider')}; } '''; }
flutter/dev/tools/gen_defaults/lib/search_view_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/search_view_template.dart", "repo_id": "flutter", "token_count": 574 }
600
// 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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_TESTING_KEY_CODES_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_TESTING_KEY_CODES_H_ #include <cinttypes> // 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 // flutter/flutter:dev/tools/gen_keycodes/data/key_codes_cc.tmpl // instead. // // See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. // This file contains keyboard constants to be used in unit tests. They should // not be used in production code. namespace flutter { namespace testing { namespace keycodes { @@@PHYSICAL_KEY_DEFINITIONS@@@ @@@LOGICAL_KEY_DEFINITIONS@@@ } // namespace keycodes } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_TESTING_KEY_CODES_H_
flutter/dev/tools/gen_keycodes/data/key_codes_h.tmpl/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/key_codes_h.tmpl", "repo_id": "flutter", "token_count": 366 }
601
{ "Cancel": ["CANCEL"], "Backspace": ["BACK"], "Tab": ["TAB"], "Clear": ["CLEAR"], "Enter": ["RETURN"], "Menu": ["MENU"], "Pause": ["PAUSE"], "CapsLock": ["CAPITAL"], "Lang1": ["HANGUL", "HANGEUL", "KANA"], "JunjaMode": ["JUNJA"], "FinalMode": ["FINAL"], "KanjiMode": ["KANJI", "HANJA"], "Escape": ["ESCAPE"], "Convert": ["CONVERT"], "Nonconvert": ["NONCONVERT"], "Accept": ["ACCEPT"], "ModeChange": ["MODECHANGE"], "Space": ["SPACE"], "Home": ["HOME"], "End": ["END"], "ArrowLeft": ["LEFT"], "ArrowUp": ["UP"], "ArrowRight": ["RIGHT"], "ArrowDown": ["DOWN"], "Sleep": ["SLEEP"], "Select": ["SELECT"], "Print": ["PRINT"], "Execute": ["EXECUTE"], "Insert": ["INSERT"], "Delete": ["DELETE"], "Help": ["HELP"], "MetaLeft": ["LWIN"], "MetaRight": ["RWIN"], "ContextMenu": ["APPS"], "PageDown": ["NEXT"], "PageUp": ["PRIOR"], "PrintScreen": ["SNAPSHOT"], "Numpad0": ["NUMPAD0"], "Numpad1": ["NUMPAD1"], "Numpad2": ["NUMPAD2"], "Numpad3": ["NUMPAD3"], "Numpad4": ["NUMPAD4"], "Numpad5": ["NUMPAD5"], "Numpad6": ["NUMPAD6"], "Numpad7": ["NUMPAD7"], "Numpad8": ["NUMPAD8"], "Numpad9": ["NUMPAD9"], "NumpadMultiply": ["MULTIPLY"], "NumpadAdd": ["ADD"], "NumpadComma": ["SEPARATOR"], "NumpadSubtract": ["SUBTRACT"], "NumpadDecimal": ["DECIMAL"], "NumpadDivide": ["DIVIDE"], "F1": ["F1"], "F2": ["F2"], "F3": ["F3"], "F4": ["F4"], "F5": ["F5"], "F6": ["F6"], "F7": ["F7"], "F8": ["F8"], "F9": ["F9"], "F10": ["F10"], "F11": ["F11"], "F12": ["F12"], "F13": ["F13"], "F14": ["F14"], "F15": ["F15"], "F16": ["F16"], "F17": ["F17"], "F18": ["F18"], "F19": ["F19"], "F20": ["F20"], "F21": ["F21"], "F22": ["F22"], "F23": ["F23"], "F24": ["F24"], "NavigationView": ["NAVIGATION_VIEW"], "NavigationMenu": ["NAVIGATION_MENU"], "NavigationUp": ["NAVIGATION_UP"], "NavigationDown": ["NAVIGATION_DOWN"], "NavigationLeft": ["NAVIGATION_LEFT"], "NavigationRight": ["NAVIGATION_RIGHT"], "NavigationAccept": ["NAVIGATION_ACCEPT"], "NavigationCancel": ["NAVIGATION_CANCEL"], "NumLock": ["NUMLOCK"], "ScrollLock": ["SCROLL"], "NumpadEqual": ["OEM_NEC_EQUAL"], "ShiftLeft": ["LSHIFT", "SHIFT"], "ShiftRight": ["RSHIFT"], "ShiftLock": ["OEM_SHIFT"], "ControlLeft": ["LCONTROL", "CONTROL"], "ControlRight": ["RCONTROL"], "AltLeft": ["LMENU"], "AltRight": ["RMENU"], "BrowserBack": ["BROWSER_BACK"], "BrowserForward": ["BROWSER_FORWARD"], "BrowserRefresh": ["BROWSER_REFRESH"], "BrowserStop": ["BROWSER_STOP"], "BrowserSearch": ["BROWSER_SEARCH"], "BrowserFavorites": ["BROWSER_FAVORITES"], "BrowserHome": ["BROWSER_HOME"], "AudioVolumeMute": ["VOLUME_MUTE"], "AudioVolumeDown": ["VOLUME_DOWN"], "AudioVolumeUp": ["VOLUME_UP"], "MediaNextTrack": ["MEDIA_NEXT_TRACK"], "MediaPrevTrack": ["MEDIA_PREV_TRACK"], "MediaStop": ["MEDIA_STOP"], "MediaPlayPause": ["MEDIA_PLAY_PAUSE"], "LaunchMail": ["LAUNCH_MAIL"], "LaunchMediaSelect": ["LAUNCH_MEDIA_SELECT"], "LaunchApp1": ["LAUNCH_APP1"], "LaunchApp2": ["LAUNCH_APP2"], "Semicolon": ["OEM_1"], "Equal": ["OEM_PLUS"], "Comma": ["OEM_COMMA"], "Minus": ["OEM_MINUS"], "Period": ["OEM_PERIOD"], "Slash": ["OEM_2"], "Backquote": ["OEM_3"], "GameButton8": ["GAMEPAD_A"], "GameButton9": ["GAMEPAD_B"], "GameButton10": ["GAMEPAD_X"], "GameButton11": ["GAMEPAD_Y"], "GameButton12": ["GAMEPAD_RIGHT_SHOULDER"], "GameButton13": ["GAMEPAD_LEFT_SHOULDER"], "GameButton14": ["GAMEPAD_LEFT_TRIGGER"], "GameButton15": ["GAMEPAD_RIGHT_TRIGGER"], "GameButton16": ["GAMEPAD_DPAD_UP"], "GameButton17": ["GAMEPAD_DPAD_DOWN"], "GameButton18": ["GAMEPAD_DPAD_LEFT"], "GameButton19": ["GAMEPAD_DPAD_RIGHT"], "GamepadMenu": ["GAMEPAD_MENU"], "GamepadView": ["GAMEPAD_VIEW"], "GamepadLeftThumbstickButton": ["GAMEPAD_LEFT_THUMBSTICK_BUTTON"], "GamepadRightThumbstickButton": ["GAMEPAD_RIGHT_THUMBSTICK_BUTTON"], "GamepadLeftThumbstickUp": ["GAMEPAD_LEFT_THUMBSTICK_UP"], "GamepadLeftThumbstickDown": ["GAMEPAD_LEFT_THUMBSTICK_DOWN"], "GamepadLeftThumbstickRight": ["GAMEPAD_LEFT_THUMBSTICK_RIGHT"], "GamepadLeftThumbstickLeft": ["GAMEPAD_LEFT_THUMBSTICK_LEFT"], "GamepadRightThumbstickUp": ["GAMEPAD_RIGHT_THUMBSTICK_UP"], "GamepadRightThumbstickDown": ["GAMEPAD_RIGHT_THUMBSTICK_DOWN"], "GamepadRightThumbstickRight": ["GAMEPAD_RIGHT_THUMBSTICK_RIGHT"], "GamepadRightThumbstickLeft": ["GAMEPAD_RIGHT_THUMBSTICK_LEFT"], "BracketLeft": ["OEM_4"], "Backslash": ["OEM_5"], "BracketRight": ["OEM_6"], "Quote": ["OEM_7"], "Oem8": ["OEM_8"], "OemAx": ["OEM_AX"], "Oem102": ["OEM_102"], "IcoHelp": ["ICO_HELP"], "Ico00": ["ICO_00"], "Processkey": ["PROCESSKEY"], "IcoClear": ["ICO_CLEAR"], "Packet": ["PACKET"], "OemReset": ["OEM_RESET"], "OemJump": ["OEM_JUMP"], "OemPa1": ["OEM_PA1"], "OemPa2": ["OEM_PA2"], "OemPa3": ["OEM_PA3"], "OemWsctrl": ["OEM_WSCTRL"], "OemCusel": ["OEM_CUSEL"], "OemAttn": ["OEM_ATTN"], "OemFinish": ["OEM_FINISH"], "OemCopy": ["OEM_COPY"], "OemAuto": ["OEM_AUTO"], "OemEnlw": ["OEM_ENLW"], "OemBacktab": ["OEM_BACKTAB"], "Attn": ["ATTN"], "Crsel": ["CRSEL"], "Exsel": ["EXSEL"], "Ereof": ["EREOF"], "Play": ["PLAY"], "Zoom": ["ZOOM"], "Noname": ["NONAME"], "Pa1": ["PA1"], "OemClear": ["OEM_CLEAR"] }
flutter/dev/tools/gen_keycodes/data/windows_logical_to_window_vk.json/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/windows_logical_to_window_vk.json", "repo_id": "flutter", "token_count": 2447 }
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:path/path.dart' as path; import 'base_code_gen.dart'; import 'constants.dart'; import 'logical_key_data.dart'; import 'physical_key_data.dart'; import 'utils.dart'; /// Generates the key mapping for Web, based on the information in the key /// data structure given to it. class WebCodeGenerator extends PlatformCodeGenerator { WebCodeGenerator( super.keyData, super.logicalData, String logicalLocationMap, ) : _logicalLocationMap = parseMapOfListOfNullableString(logicalLocationMap); /// This generates the map of Web KeyboardEvent codes to logical key ids. String get _webLogicalKeyCodeMap { final OutputLines<String> lines = OutputLines<String>('Web logical map'); for (final LogicalKeyEntry entry in logicalData.entries) { final int plane = getPlane(entry.value); if (plane == kUnprintablePlane.value) { for (final String name in entry.webNames) { lines.add(name, " '$name': ${toHex(entry.value, digits: 11)},"); } } } return lines.sortedJoin().trimRight(); } /// This generates the map of Web KeyboardEvent codes to physical key USB HID codes. String get _webPhysicalKeyCodeMap { final OutputLines<String> lines = OutputLines<String>('Web physical map'); for (final PhysicalKeyEntry entry in keyData.entries) { for (final String webCode in entry.webCodes()) { lines.add(webCode, " '$webCode': ${toHex(entry.usbHidCode)}, // ${entry.constantName}"); } } return lines.sortedJoin().trimRight(); } /// This generates the map of Web number pad codes to logical key ids. String get _webLogicalLocationMap { final OutputLines<String> lines = OutputLines<String>('Web logical location map'); _logicalLocationMap.forEach((String webKey, List<String?> locations) { final String valuesString = locations.map((String? value) { return value == null ? 'null' : toHex(logicalData.entryByName(value).value, digits: 11); }).join(', '); final String namesString = locations.map((String? value) { return value == null ? 'null' : logicalData.entryByName(value).constantName; }).join(', '); lines.add(webKey, " '$webKey': <int?>[$valuesString], // $namesString"); }); return lines.sortedJoin().trimRight(); } final Map<String, List<String?>> _logicalLocationMap; @override String get templatePath => path.join(dataRoot, 'web_key_map_dart.tmpl'); @override String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot, 'lib', 'web_ui', 'lib', 'src', 'engine', 'key_map.g.dart'); @override Map<String, String> mappings() { return <String, String>{ 'WEB_LOGICAL_KEY_CODE_MAP': _webLogicalKeyCodeMap, 'WEB_PHYSICAL_KEY_CODE_MAP': _webPhysicalKeyCodeMap, 'WEB_LOGICAL_LOCATION_MAP': _webLogicalLocationMap, }; } }
flutter/dev/tools/gen_keycodes/lib/web_code_gen.dart/0
{ "file_path": "flutter/dev/tools/gen_keycodes/lib/web_code_gen.dart", "repo_id": "flutter", "token_count": 1094 }
603
<svg id="svg_build_00" xmlns="http://www.w3.org/2000/svg" width="100px" height="100px" > <path id="path_1" d="M 50.0 50.0 l 10.0 0 l 0.0 10.0 z l 0.0 -10.0 l -10.0 0.0 z " fill="#000000" /> </svg>
flutter/dev/tools/vitool/test_assets/close_path_in_middle.svg/0
{ "file_path": "flutter/dev/tools/vitool/test_assets/close_path_in_middle.svg", "repo_id": "flutter", "token_count": 100 }
604
// 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:developer' as developer; import 'dart:isolate' as isolate; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service_io.dart'; export 'package:vm_service/vm_service.dart' show TimelineEvent; late String isolateId; late VmService _vmService; void initTimelineTests() { setUpAll(() async { final developer.ServiceProtocolInfo info = await developer.Service.getInfo(); if (info.serverUri == null) { fail('This test _must_ be run with --enable-vmservice.'); } _vmService = await vmServiceConnectUri('ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws'); await _vmService.setVMTimelineFlags(<String>['Dart']); isolateId = developer.Service.getIsolateId(isolate.Isolate.current)!; }); } Future<List<TimelineEvent>> fetchTimelineEvents() async { final Timeline timeline = await _vmService.getVMTimeline(); await _vmService.clearVMTimeline(); return timeline.traceEvents!; } Future<List<TimelineEvent>> fetchInterestingEvents(Set<String> interestingLabels) async { return (await fetchTimelineEvents()).where((TimelineEvent event) { return interestingLabels.contains(event.json!['name']) && event.json!['ph'] == 'B'; // "Begin" mark of events, vs E which is for the "End" mark of events. }).toList(); } String eventToName(TimelineEvent event) => event.json!['name'] as String; Future<List<String>> fetchInterestingEventNames(Set<String> interestingLabels) async { return (await fetchInterestingEvents(interestingLabels)).map<String>(eventToName).toList(); } Future<void> runFrame(VoidCallback callback) { final Future<void> result = SchedulerBinding.instance.endOfFrame; // schedules a frame callback(); return result; } // This binding skips the zones tests. These tests were written before we // verified zones properly, and they have been legacied-in to avoid having // to refactor them. // // When creating new tests, avoid relying on this class. class ZoneIgnoringTestBinding extends WidgetsFlutterBinding { @override void initInstances() { super.initInstances(); _instance = this; } @override bool debugCheckZone(String entryPoint) { return true; } static ZoneIgnoringTestBinding get instance => BindingBase.checkInstance(_instance); static ZoneIgnoringTestBinding? _instance; static ZoneIgnoringTestBinding ensureInitialized() { if (ZoneIgnoringTestBinding._instance == null) { ZoneIgnoringTestBinding(); } return ZoneIgnoringTestBinding.instance; } }
flutter/dev/tracing_tests/test/common.dart/0
{ "file_path": "flutter/dev/tracing_tests/test/common.dart", "repo_id": "flutter", "token_count": 905 }
605
package dev.flutter.flutter_api_samples import io.flutter.embedding.android.FlutterActivity class MainActivity : FlutterActivity()
flutter/examples/api/android/app/src/main/kotlin/dev/flutter/flutter_api_samples/MainActivity.kt/0
{ "file_path": "flutter/examples/api/android/app/src/main/kotlin/dev/flutter/flutter_api_samples/MainActivity.kt", "repo_id": "flutter", "token_count": 40 }
606
// 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 inset [CupertinoListSection] and [CupertinoListTile]. void main() => runApp(const CupertinoListSectionInsetApp()); class CupertinoListSectionInsetApp extends StatelessWidget { const CupertinoListSectionInsetApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( home: ListSectionInsetExample(), ); } } class ListSectionInsetExample extends StatelessWidget { const ListSectionInsetExample({super.key}); @override Widget build(BuildContext context) { return CupertinoPageScaffold( child: CupertinoListSection.insetGrouped( header: const Text('My Reminders'), children: <CupertinoListTile>[ CupertinoListTile.notched( title: const Text('Open pull request'), leading: Container( width: double.infinity, height: double.infinity, color: CupertinoColors.activeGreen, ), trailing: const CupertinoListTileChevron(), onTap: () => Navigator.of(context).push( CupertinoPageRoute<void>( builder: (BuildContext context) { return const _SecondPage(text: 'Open pull request'); }, ), ), ), CupertinoListTile.notched( title: const Text('Push to master'), leading: Container( width: double.infinity, height: double.infinity, color: CupertinoColors.systemRed, ), additionalInfo: const Text('Not available'), ), CupertinoListTile.notched( title: const Text('View last commit'), leading: Container( width: double.infinity, height: double.infinity, color: CupertinoColors.activeOrange, ), additionalInfo: const Text('12 days ago'), trailing: const CupertinoListTileChevron(), onTap: () => Navigator.of(context).push( CupertinoPageRoute<void>( builder: (BuildContext context) { return const _SecondPage(text: 'Last commit'); }, ), ), ), ], ), ); } } class _SecondPage extends StatelessWidget { const _SecondPage({required this.text}); final String text; @override Widget build(BuildContext context) { return CupertinoPageScaffold( child: Center( child: Text(text), ), ); } }
flutter/examples/api/lib/cupertino/list_section/list_section_inset.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/list_section/list_section_inset.0.dart", "repo_id": "flutter", "token_count": 1244 }
607
// 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 [CupertinoSlider]. void main() => runApp(const CupertinoSliderApp()); class CupertinoSliderApp extends StatelessWidget { const CupertinoSliderApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: CupertinoSliderExample(), ); } } class CupertinoSliderExample extends StatefulWidget { const CupertinoSliderExample({super.key}); @override State<CupertinoSliderExample> createState() => _CupertinoSliderExampleState(); } class _CupertinoSliderExampleState extends State<CupertinoSliderExample> { double _currentSliderValue = 0.0; String? _sliderStatus; @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('CupertinoSlider Sample'), ), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ // Display the current slider value. Text('$_currentSliderValue'), CupertinoSlider( key: const Key('slider'), value: _currentSliderValue, // This allows the slider to jump between divisions. // If null, the slide movement is continuous. divisions: 5, // The maximum slider value max: 100, activeColor: CupertinoColors.systemPurple, thumbColor: CupertinoColors.systemPurple, // This is called when sliding is started. onChangeStart: (double value) { setState(() { _sliderStatus = 'Sliding'; }); }, // This is called when sliding has ended. onChangeEnd: (double value) { setState(() { _sliderStatus = 'Finished sliding'; }); }, // This is called when slider value is changed. onChanged: (double value) { setState(() { _currentSliderValue = value; }); }, ), Text( _sliderStatus ?? '', style: CupertinoTheme.of(context).textTheme.textStyle.copyWith( fontSize: 12, ), ), ], ), ), ); } }
flutter/examples/api/lib/cupertino/slider/cupertino_slider.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/slider/cupertino_slider.0.dart", "repo_id": "flutter", "token_count": 1238 }
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 'package:flutter/material.dart'; /// Flutter code sample for [AppBar]. void main() => runApp(const AppBarApp()); class AppBarApp extends StatelessWidget { const AppBarApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: AppBarExample(), ); } } class AppBarExample extends StatelessWidget { const AppBarExample({super.key}); @override Widget build(BuildContext context) { final ButtonStyle style = TextButton.styleFrom( foregroundColor: Theme.of(context).colorScheme.onPrimary, ); return Scaffold( appBar: AppBar( actions: <Widget>[ TextButton( style: style, onPressed: () {}, child: const Text('Action 1'), ), TextButton( style: style, onPressed: () {}, child: const Text('Action 2'), ), ], ), ); } }
flutter/examples/api/lib/material/app_bar/app_bar.2.dart/0
{ "file_path": "flutter/examples/api/lib/material/app_bar/app_bar.2.dart", "repo_id": "flutter", "token_count": 448 }
609
// 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 [BottomNavigationBar]. void main() => runApp(const BottomNavigationBarExampleApp()); class BottomNavigationBarExampleApp extends StatelessWidget { const BottomNavigationBarExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: BottomNavigationBarExample(), ); } } class BottomNavigationBarExample extends StatefulWidget { const BottomNavigationBarExample({super.key}); @override State<BottomNavigationBarExample> createState() => _BottomNavigationBarExampleState(); } class _BottomNavigationBarExampleState extends State<BottomNavigationBarExample> { int _selectedIndex = 0; static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold); static const List<Widget> _widgetOptions = <Widget>[ Text( 'Index 0: Home', style: optionStyle, ), Text( 'Index 1: Business', style: optionStyle, ), Text( 'Index 2: School', style: optionStyle, ), Text( 'Index 3: Settings', style: optionStyle, ), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('BottomNavigationBar Sample'), ), body: Center( child: _widgetOptions.elementAt(_selectedIndex), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', backgroundColor: Colors.red, ), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'Business', backgroundColor: Colors.green, ), BottomNavigationBarItem( icon: Icon(Icons.school), label: 'School', backgroundColor: Colors.purple, ), BottomNavigationBarItem( icon: Icon(Icons.settings), label: 'Settings', backgroundColor: Colors.pink, ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.amber[800], onTap: _onItemTapped, ), ); } }
flutter/examples/api/lib/material/bottom_navigation_bar/bottom_navigation_bar.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/bottom_navigation_bar/bottom_navigation_bar.1.dart", "repo_id": "flutter", "token_count": 1016 }
610
// 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 [DeletableChipAttributes.deleteIconBoxConstraints]. void main() => runApp(const DeleteIconBoxConstraintsApp()); class DeleteIconBoxConstraintsApp extends StatelessWidget { const DeleteIconBoxConstraintsApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: DeleteIconBoxConstraintsExample(), ), ), ); } } class DeleteIconBoxConstraintsExample extends StatelessWidget { const DeleteIconBoxConstraintsExample({super.key}); @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RawChip( deleteIconBoxConstraints: const BoxConstraints.tightForFinite(), onDeleted: () {}, label: const SizedBox( width: 150, child: Text( 'One line text.', maxLines: 3, overflow: TextOverflow.ellipsis, ), ), ), const SizedBox(height: 10), RawChip( deleteIconBoxConstraints: const BoxConstraints.tightForFinite(), onDeleted: () {}, label: const SizedBox( width: 150, child: Text( 'This text will wrap into two lines.', maxLines: 3, overflow: TextOverflow.ellipsis, ), ), ), const SizedBox(height: 10), RawChip( deleteIconBoxConstraints: const BoxConstraints.tightForFinite(), onDeleted: () {}, label: const SizedBox( width: 150, child: Text( 'This is a very long text that will wrap into three lines.', maxLines: 3, overflow: TextOverflow.ellipsis, ), ), ), ], ); } }
flutter/examples/api/lib/material/chip/deletable_chip_attributes.delete_icon_box_constraints.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/chip/deletable_chip_attributes.delete_icon_box_constraints.0.dart", "repo_id": "flutter", "token_count": 974 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for [AlertDialog]. void main() => runApp(const AlertDialogExampleApp()); class AlertDialogExampleApp extends StatelessWidget { const AlertDialogExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('AlertDialog Sample')), body: const Center( child: DialogExample(), ), ), ); } } class DialogExample extends StatelessWidget { const DialogExample({super.key}); @override Widget build(BuildContext context) { return TextButton( onPressed: () => showDialog<String>( context: context, builder: (BuildContext context) => AlertDialog( title: const Text('AlertDialog Title'), content: const Text('AlertDialog description'), actions: <Widget>[ TextButton( onPressed: () => Navigator.pop(context, 'Cancel'), child: const Text('Cancel'), ), TextButton( onPressed: () => Navigator.pop(context, 'OK'), child: const Text('OK'), ), ], ), ), child: const Text('Show Dialog'), ); } }
flutter/examples/api/lib/material/dialog/alert_dialog.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/dialog/alert_dialog.0.dart", "repo_id": "flutter", "token_count": 580 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for the [DropdownMenuEntry] `labelWidget` property. enum ColorItem { blue('Blue', Colors.blue), pink('Pink', Colors.pink), green('Green', Colors.green), yellow('Yellow', Colors.yellow), grey('Grey', Colors.grey); const ColorItem(this.label, this.color); final String label; final Color color; } class DropdownMenuEntryLabelWidgetExample extends StatefulWidget { const DropdownMenuEntryLabelWidgetExample({ super.key }); @override State<DropdownMenuEntryLabelWidgetExample> createState() => _DropdownMenuEntryLabelWidgetExampleState(); } class _DropdownMenuEntryLabelWidgetExampleState extends State<DropdownMenuEntryLabelWidgetExample> { late final TextEditingController controller; @override void initState() { super.initState(); controller = TextEditingController(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // Created by Google Bard from 'create a lyrical phrase of about 25 words that begins with "is a color"'. const String longText = 'is a color that sings of hope, A hue that shines like gold. It is the color of dreams, A shade that never grows old.'; return Scaffold( body: Center( child: DropdownMenu<ColorItem>( width: 300, controller: controller, initialSelection: ColorItem.green, label: const Text('Color'), onSelected: (ColorItem? color) { print('Selected $color'); }, dropdownMenuEntries: ColorItem.values.map<DropdownMenuEntry<ColorItem>>((ColorItem item) { final String labelText = '${item.label} $longText\n'; return DropdownMenuEntry<ColorItem>( value: item, label: labelText, // Try commenting the labelWidget out or changing // the labelWidget's Text parameters. labelWidget: Text( labelText, maxLines: 1, overflow: TextOverflow.ellipsis, ), ); }).toList(), ), ), ); } } class DropdownMenuEntryLabelWidgetExampleApp extends StatelessWidget { const DropdownMenuEntryLabelWidgetExampleApp({ super.key }); @override Widget build(BuildContext context) { return const MaterialApp( home: DropdownMenuEntryLabelWidgetExample(), ); } } void main() { runApp(const DropdownMenuEntryLabelWidgetExampleApp()); }
flutter/examples/api/lib/material/dropdown_menu/dropdown_menu_entry_label_widget.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/dropdown_menu/dropdown_menu_entry_label_widget.0.dart", "repo_id": "flutter", "token_count": 991 }
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 'package:flutter/material.dart'; /// Flutter code sample for [IconButton]. void main() { runApp(const IconButtonApp()); } class IconButtonApp extends StatelessWidget { const IconButtonApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(colorSchemeSeed: const Color(0xff6750a4), useMaterial3: true), title: 'Icon Button Types', home: const Scaffold( body: ButtonTypesExample(), ), ); } } class ButtonTypesExample extends StatelessWidget { const ButtonTypesExample({super.key}); @override Widget build(BuildContext context) { return const Padding( padding: EdgeInsets.all(4.0), child: Row( children: <Widget>[ Spacer(), ButtonTypesGroup(enabled: true), ButtonTypesGroup(enabled: false), Spacer(), ], ), ); } } class ButtonTypesGroup extends StatelessWidget { const ButtonTypesGroup({super.key, required this.enabled}); final bool enabled; @override Widget build(BuildContext context) { final VoidCallback? onPressed = enabled ? () {} : null; return Padding( padding: const EdgeInsets.all(4.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ IconButton(icon: const Icon(Icons.filter_drama), onPressed: onPressed), // Filled icon button IconButton.filled(onPressed: onPressed, icon: const Icon(Icons.filter_drama)), // Filled tonal icon button IconButton.filledTonal(onPressed: onPressed, icon: const Icon(Icons.filter_drama)), // Outlined icon button IconButton.outlined(onPressed: onPressed, icon: const Icon(Icons.filter_drama)), ], ), ); } }
flutter/examples/api/lib/material/icon_button/icon_button.2.dart/0
{ "file_path": "flutter/examples/api/lib/material/icon_button/icon_button.2.dart", "repo_id": "flutter", "token_count": 757 }
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'; /// Flutter code sample for [MaterialStateProperty]. void main() => runApp(const MaterialStatePropertyExampleApp()); class MaterialStatePropertyExampleApp extends StatelessWidget { const MaterialStatePropertyExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('MaterialStateProperty Sample')), body: const Center( child: MaterialStatePropertyExample(), ), ), ); } } class MaterialStatePropertyExample extends StatelessWidget { const MaterialStatePropertyExample({super.key}); @override Widget build(BuildContext context) { Color getColor(Set<MaterialState> states) { const Set<MaterialState> interactiveStates = <MaterialState>{ MaterialState.pressed, MaterialState.hovered, MaterialState.focused, }; if (states.any(interactiveStates.contains)) { return Colors.blue; } return Colors.red; } return TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith(getColor), ), onPressed: () {}, child: const Text('TextButton'), ); } }
flutter/examples/api/lib/material/material_state/material_state_property.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/material_state/material_state_property.0.dart", "repo_id": "flutter", "token_count": 491 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for [PageTransitionsTheme]. void main() => runApp(const PageTransitionsThemeApp()); class PageTransitionsThemeApp extends StatelessWidget { const PageTransitionsThemeApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( useMaterial3: true, // Defines the page transition animations used by MaterialPageRoute // for different target platforms. // Non-specified target platforms will default to // ZoomPageTransitionsBuilder(). pageTransitionsTheme: const PageTransitionsTheme( builders: <TargetPlatform, PageTransitionsBuilder>{ TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), TargetPlatform.linux: OpenUpwardsPageTransitionsBuilder(), TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(), }, ), ), home: const HomePage(), ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.blueGrey, body: Center( child: ElevatedButton( onPressed: () { Navigator.of(context).push( MaterialPageRoute<SecondPage>( builder: (BuildContext context) => const SecondPage(), ), ); }, child: const Text('To SecondPage'), ), ), ); } } class SecondPage extends StatelessWidget { const SecondPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.purple[200], body: Center( child: ElevatedButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Back to HomePage'), ), ), ); } }
flutter/examples/api/lib/material/page_transitions_theme/page_transitions_theme.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/page_transitions_theme/page_transitions_theme.0.dart", "repo_id": "flutter", "token_count": 825 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for [RadioListTile]. void main() => runApp(const RadioListTileApp()); class RadioListTileApp extends StatelessWidget { const RadioListTileApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('RadioListTile Sample')), body: const RadioListTileExample(), ), ); } } enum SingingCharacter { lafayette, jefferson } class RadioListTileExample extends StatefulWidget { const RadioListTileExample({super.key}); @override State<RadioListTileExample> createState() => _RadioListTileExampleState(); } class _RadioListTileExampleState extends State<RadioListTileExample> { SingingCharacter? _character = SingingCharacter.lafayette; @override Widget build(BuildContext context) { return Column( children: <Widget>[ RadioListTile<SingingCharacter>( title: const Text('Lafayette'), value: SingingCharacter.lafayette, groupValue: _character, onChanged: (SingingCharacter? value) { setState(() { _character = value; }); }, ), RadioListTile<SingingCharacter>( title: const Text('Thomas Jefferson'), value: SingingCharacter.jefferson, groupValue: _character, onChanged: (SingingCharacter? value) { setState(() { _character = value; }); }, ), ], ); } }
flutter/examples/api/lib/material/radio_list_tile/radio_list_tile.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/radio_list_tile/radio_list_tile.0.dart", "repo_id": "flutter", "token_count": 691 }
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/material.dart'; /// Flutter code sample for [Scaffold.of]. void main() => runApp(const OfExampleApp()); class OfExampleApp extends StatelessWidget { const OfExampleApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( body: const MyScaffoldBody(), appBar: AppBar(title: const Text('Scaffold.of Example')), ), color: Colors.white, ); } } class MyScaffoldBody extends StatelessWidget { const MyScaffoldBody({super.key}); @override Widget build(BuildContext context) { return Center( child: ElevatedButton( child: const Text('SHOW BOTTOM SHEET'), onPressed: () { Scaffold.of(context).showBottomSheet( (BuildContext context) { return Container( alignment: Alignment.center, height: 200, color: Colors.amber, child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('BottomSheet'), ElevatedButton( child: const Text('Close BottomSheet'), onPressed: () { Navigator.pop(context); }, ), ], ), ), ); }, ); }, ), ); } }
flutter/examples/api/lib/material/scaffold/scaffold.of.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/scaffold/scaffold.of.0.dart", "repo_id": "flutter", "token_count": 901 }
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 'dart:async'; import 'package:flutter/material.dart'; /// Flutter code sample for [SearchAnchor]. const Duration fakeAPIDuration = Duration(seconds: 1); const Duration debounceDuration = Duration(milliseconds: 500); void main() => runApp(const SearchAnchorAsyncExampleApp()); class SearchAnchorAsyncExampleApp extends StatelessWidget { const SearchAnchorAsyncExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('SearchAnchor - async and debouncing'), ), body: const Center( child: _AsyncSearchAnchor(), ), ), ); } } class _AsyncSearchAnchor extends StatefulWidget { const _AsyncSearchAnchor(); @override State<_AsyncSearchAnchor > createState() => _AsyncSearchAnchorState(); } class _AsyncSearchAnchorState extends State<_AsyncSearchAnchor > { // The query currently being searched for. If null, there is no pending // request. String? _currentQuery; // The most recent suggestions received from the API. late Iterable<Widget> _lastOptions = <Widget>[]; late final _Debounceable<Iterable<String>?, String> _debouncedSearch; // Calls the "remote" API to search with the given query. Returns null when // the call has been made obsolete. Future<Iterable<String>?> _search(String query) async { _currentQuery = query; // In a real application, there should be some error handling here. final Iterable<String> options = await _FakeAPI.search(_currentQuery!); // If another search happened after this one, throw away these options. if (_currentQuery != query) { return null; } _currentQuery = null; return options; } @override void initState() { super.initState(); _debouncedSearch = _debounce<Iterable<String>?, String>(_search); } @override Widget build(BuildContext context) { return SearchAnchor( builder: (BuildContext context, SearchController controller) { return IconButton( icon: const Icon(Icons.search), onPressed: () { controller.openView(); }, ); }, suggestionsBuilder: (BuildContext context, SearchController controller) async { final List<String>? options = (await _debouncedSearch(controller.text))?.toList(); if (options == null) { return _lastOptions; } _lastOptions = List<ListTile>.generate(options.length, (int index) { final String item = options[index]; return ListTile( title: Text(item), onTap: () { debugPrint('You just selected $item'); }, ); }); return _lastOptions; }, ); } } // Mimics a remote API. class _FakeAPI { static const List<String> _kOptions = <String>[ 'aardvark', 'bobcat', 'chameleon', ]; // Searches the options, but injects a fake "network" delay. static Future<Iterable<String>> search(String query) async { await Future<void>.delayed(fakeAPIDuration); // Fake 1 second delay. if (query == '') { return const Iterable<String>.empty(); } return _kOptions.where((String option) { return option.contains(query.toLowerCase()); }); } } typedef _Debounceable<S, T> = Future<S?> Function(T parameter); /// Returns a new function that is a debounced version of the given function. /// /// This means that the original function will be called only after no calls /// have been made for the given Duration. _Debounceable<S, T> _debounce<S, T>(_Debounceable<S?, T> function) { _DebounceTimer? debounceTimer; return (T parameter) async { if (debounceTimer != null && !debounceTimer!.isCompleted) { debounceTimer!.cancel(); } debounceTimer = _DebounceTimer(); try { await debounceTimer!.future; } catch (error) { if (error is _CancelException) { return null; } rethrow; } return function(parameter); }; } // A wrapper around Timer used for debouncing. class _DebounceTimer { _DebounceTimer() { _timer = Timer(debounceDuration, _onComplete); } late final Timer _timer; final Completer<void> _completer = Completer<void>(); void _onComplete() { _completer.complete(); } Future<void> get future => _completer.future; bool get isCompleted => _completer.isCompleted; void cancel() { _timer.cancel(); _completer.completeError(const _CancelException()); } } // An exception indicating that the timer was canceled. class _CancelException implements Exception { const _CancelException(); }
flutter/examples/api/lib/material/search_anchor/search_anchor.4.dart/0
{ "file_path": "flutter/examples/api/lib/material/search_anchor/search_anchor.4.dart", "repo_id": "flutter", "token_count": 1734 }
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 'package:flutter/material.dart'; /// Flutter code sample for [Stepper.controlsBuilder]. void main() => runApp(const ControlsBuilderExampleApp()); class ControlsBuilderExampleApp extends StatelessWidget { const ControlsBuilderExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Stepper Sample')), body: const ControlsBuilderExample(), ), ); } } class ControlsBuilderExample extends StatelessWidget { const ControlsBuilderExample({super.key}); @override Widget build(BuildContext context) { return Stepper( controlsBuilder: (BuildContext context, ControlsDetails details) { return Row( children: <Widget>[ TextButton( onPressed: details.onStepContinue, child: const Text('NEXT'), ), TextButton( onPressed: details.onStepCancel, child: const Text('CANCEL'), ), ], ); }, steps: const <Step>[ Step( title: Text('A'), content: SizedBox( width: 100.0, height: 100.0, ), ), Step( title: Text('B'), content: SizedBox( width: 100.0, height: 100.0, ), ), ], ); } }
flutter/examples/api/lib/material/stepper/stepper.controls_builder.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/stepper/stepper.controls_builder.0.dart", "repo_id": "flutter", "token_count": 695 }
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. import 'package:flutter/material.dart'; /// Flutter code sample for [TextField]. class ObscuredTextFieldSample extends StatelessWidget { const ObscuredTextFieldSample({super.key}); @override Widget build(BuildContext context) { return const SizedBox( width: 250, child: TextField( obscureText: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ); } } class TextFieldExampleApp extends StatelessWidget { const TextFieldExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Obscured Textfield')), body: const Center( child: ObscuredTextFieldSample(), ), ), ); } } void main() => runApp(const TextFieldExampleApp());
flutter/examples/api/lib/material/text_field/text_field.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/text_field/text_field.0.dart", "repo_id": "flutter", "token_count": 387 }
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 'dart:async'; import 'dart:io'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @immutable class CustomNetworkImage extends ImageProvider<Uri> { const CustomNetworkImage(this.url); final String url; @override Future<Uri> obtainKey(ImageConfiguration configuration) { final Uri result = Uri.parse(url).replace( queryParameters: <String, String>{ 'dpr': '${configuration.devicePixelRatio}', 'locale': '${configuration.locale?.toLanguageTag()}', 'platform': '${configuration.platform?.name}', 'width': '${configuration.size?.width}', 'height': '${configuration.size?.height}', 'bidi': '${configuration.textDirection?.name}', }, ); return SynchronousFuture<Uri>(result); } static HttpClient get _httpClient { HttpClient? client; assert(() { if (debugNetworkImageHttpClientProvider != null) { client = debugNetworkImageHttpClientProvider!(); } return true; }()); return client ?? HttpClient()..autoUncompress = false; } @override ImageStreamCompleter loadImage(Uri key, ImageDecoderCallback decode) { final StreamController<ImageChunkEvent> chunkEvents = StreamController<ImageChunkEvent>(); debugPrint('Fetching "$key"...'); return MultiFrameImageStreamCompleter( codec: _httpClient.getUrl(key) .then<HttpClientResponse>((HttpClientRequest request) => request.close()) .then<Uint8List>((HttpClientResponse response) { return consolidateHttpClientResponseBytes( response, onBytesReceived: (int cumulative, int? total) { chunkEvents.add(ImageChunkEvent( cumulativeBytesLoaded: cumulative, expectedTotalBytes: total, )); }, ); }) .catchError((Object e, StackTrace stack) { scheduleMicrotask(() { PaintingBinding.instance.imageCache.evict(key); }); return Future<Uint8List>.error(e, stack); }) .whenComplete(chunkEvents.close) .then<ui.ImmutableBuffer>(ui.ImmutableBuffer.fromUint8List) .then<ui.Codec>(decode), chunkEvents: chunkEvents.stream, scale: 1.0, debugLabel: '"key"', informationCollector: () => <DiagnosticsNode>[ DiagnosticsProperty<ImageProvider>('Image provider', this), DiagnosticsProperty<Uri>('URL', key), ], ); } @override String toString() => '${objectRuntimeType(this, 'CustomNetworkImage')}("$url")'; } void main() => runApp(const ExampleApp()); class ExampleApp extends StatelessWidget { const ExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Image( image: const CustomNetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/flamingos.jpg'), width: constraints.hasBoundedWidth ? constraints.maxWidth : null, height: constraints.hasBoundedHeight ? constraints.maxHeight : null, ); }, ), ); } }
flutter/examples/api/lib/painting/image_provider/image_provider.0.dart/0
{ "file_path": "flutter/examples/api/lib/painting/image_provider/image_provider.0.dart", "repo_id": "flutter", "token_count": 1393 }
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 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// Flutter code sample for setting the [SystemUiOverlayStyle] with an [AnnotatedRegion]. void main() => runApp(const SystemOverlayStyleApp()); class SystemOverlayStyleApp extends StatelessWidget { const SystemOverlayStyleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( useMaterial3: true, brightness: Brightness.light, ), home: const SystemOverlayStyleExample(), ); } } class SystemOverlayStyleExample extends StatefulWidget { const SystemOverlayStyleExample({super.key}); @override State<SystemOverlayStyleExample> createState() => _SystemOverlayStyleExampleState(); } class _SystemOverlayStyleExampleState extends State<SystemOverlayStyleExample> { final math.Random _random = math.Random(); SystemUiOverlayStyle _currentStyle = SystemUiOverlayStyle.light; void _changeColor() { final Color color = Color.fromRGBO( _random.nextInt(255), _random.nextInt(255), _random.nextInt(255), 1.0, ); setState(() { _currentStyle = SystemUiOverlayStyle.dark.copyWith( statusBarColor: color, systemNavigationBarColor: color, ); }); } @override Widget build(BuildContext context) { return AnnotatedRegion<SystemUiOverlayStyle>( value: _currentStyle, child: Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.all(16.0), child: Text( 'SystemUiOverlayStyle Sample', style: Theme.of(context).textTheme.titleLarge, ), ), Expanded( child: Center( child: ElevatedButton( onPressed: _changeColor, child: const Text('Change Color'), ), ), ), ], ), ), ); } }
flutter/examples/api/lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.1.dart/0
{ "file_path": "flutter/examples/api/lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.1.dart", "repo_id": "flutter", "token_count": 948 }
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 'package:flutter/material.dart'; /// Flutter code sample for [AnimatedGrid]. void main() { runApp(const AnimatedGridSample()); } class AnimatedGridSample extends StatefulWidget { const AnimatedGridSample({super.key}); @override State<AnimatedGridSample> createState() => _AnimatedGridSampleState(); } class _AnimatedGridSampleState extends State<AnimatedGridSample> { final GlobalKey<AnimatedGridState> _gridKey = GlobalKey<AnimatedGridState>(); late ListModel<int> _list; int? _selectedItem; late int _nextItem; // The next item inserted when the user presses the '+' button. @override void initState() { super.initState(); _list = ListModel<int>( listKey: _gridKey, initialItems: <int>[0, 1, 2, 3, 4, 5], removedItemBuilder: _buildRemovedItem, ); _nextItem = 6; } // Used to build list items that haven't been removed. Widget _buildItem(BuildContext context, int index, Animation<double> animation) { return CardItem( animation: animation, item: _list[index], selected: _selectedItem == _list[index], onTap: () { setState(() { _selectedItem = _selectedItem == _list[index] ? null : _list[index]; }); }, ); } // Used to build an item after it has been removed from the list. This method // is needed because a removed item remains visible until its animation has // completed (even though it's gone as far as this ListModel is concerned). // The widget will be used by the [AnimatedGridState.removeItem] method's // [AnimatedGridRemovedItemBuilder] parameter. Widget _buildRemovedItem(int item, BuildContext context, Animation<double> animation) { return CardItem( animation: animation, item: item, removing: true, // No gesture detector here: we don't want removed items to be interactive. ); } // Insert the "next item" into the list model. void _insert() { final int index = _selectedItem == null ? _list.length : _list.indexOf(_selectedItem!); setState(() { _list.insert(index, _nextItem++); }); } // Remove the selected item from the list model. void _remove() { if (_selectedItem != null) { setState(() { _list.removeAt(_list.indexOf(_selectedItem!)); _selectedItem = null; }); } else if (_list.length > 0) { setState(() { _list.removeAt(_list.length - 1); }); } } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text( 'AnimatedGrid', style: TextStyle(fontSize: 30), ), centerTitle: true, leading: IconButton( icon: const Icon(Icons.remove_circle), iconSize: 32, onPressed: (_list.length > 0) ? _remove : null, tooltip: 'remove the selected item', ), actions: <Widget>[ IconButton( icon: const Icon(Icons.add_circle), iconSize: 32, onPressed: _insert, tooltip: 'insert a new item', ), ], ), body: Padding( padding: const EdgeInsets.all(16.0), child: AnimatedGrid( key: _gridKey, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 100.0, mainAxisSpacing: 10.0, crossAxisSpacing: 10.0, ), initialItemCount: _list.length, itemBuilder: _buildItem, ), ), ), ); } } typedef RemovedItemBuilder<T> = Widget Function(T item, BuildContext context, Animation<double> animation); /// Keeps a Dart [List] in sync with an [AnimatedGrid]. /// /// The [insert] and [removeAt] methods apply to both the internal list and /// the animated list that belongs to [listKey]. /// /// This class only exposes as much of the Dart List API as is needed by the /// sample app. More list methods are easily added, however methods that /// mutate the list must make the same changes to the animated list in terms /// of [AnimatedGridState.insertItem] and [AnimatedGrid.removeItem]. class ListModel<E> { ListModel({ required this.listKey, required this.removedItemBuilder, Iterable<E>? initialItems, }) : _items = List<E>.from(initialItems ?? <E>[]); final GlobalKey<AnimatedGridState> listKey; final RemovedItemBuilder<E> removedItemBuilder; final List<E> _items; AnimatedGridState? get _animatedGrid => listKey.currentState; void insert(int index, E item) { _items.insert(index, item); _animatedGrid!.insertItem( index, duration: const Duration(milliseconds: 500), ); } E removeAt(int index) { final E removedItem = _items.removeAt(index); if (removedItem != null) { _animatedGrid!.removeItem( index, (BuildContext context, Animation<double> animation) { return removedItemBuilder(removedItem, context, animation); }, ); } return removedItem; } int get length => _items.length; E operator [](int index) => _items[index]; int indexOf(E item) => _items.indexOf(item); } /// Displays its integer item as 'item N' on a Card whose color is based on /// the item's value. /// /// The text is displayed in bright green if [selected] is /// true. This widget's height is based on the [animation] parameter, it /// varies from 0 to 128 as the animation varies from 0.0 to 1.0. class CardItem extends StatelessWidget { const CardItem({ super.key, this.onTap, this.selected = false, this.removing = false, required this.animation, required this.item, }) : assert(item >= 0); final Animation<double> animation; final VoidCallback? onTap; final int item; final bool selected; final bool removing; @override Widget build(BuildContext context) { TextStyle textStyle = Theme.of(context).textTheme.headlineMedium!; if (selected) { textStyle = textStyle.copyWith(color: Colors.lightGreenAccent[400]); } return Padding( padding: const EdgeInsets.all(2.0), child: ScaleTransition( scale: CurvedAnimation(parent: animation, curve: removing ? Curves.easeInOut : Curves.bounceOut), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: onTap, child: SizedBox( height: 80.0, child: Card( color: Colors.primaries[item % Colors.primaries.length], child: Center( child: Text('${item + 1}', style: textStyle), ), ), ), ), ), ); } }
flutter/examples/api/lib/widgets/animated_grid/animated_grid.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/animated_grid/animated_grid.0.dart", "repo_id": "flutter", "token_count": 2704 }
624
// 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 [AbsorbPointer]. void main() => runApp(const AbsorbPointerApp()); class AbsorbPointerApp extends StatelessWidget { const AbsorbPointerApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('AbsorbPointer Sample')), body: const Center( child: AbsorbPointerExample(), ), ), ); } } class AbsorbPointerExample extends StatelessWidget { const AbsorbPointerExample({super.key}); @override Widget build(BuildContext context) { return Stack( alignment: AlignmentDirectional.center, children: <Widget>[ SizedBox( width: 200.0, height: 100.0, child: ElevatedButton( onPressed: () {}, child: null, ), ), SizedBox( width: 100.0, height: 200.0, child: AbsorbPointer( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue.shade200, ), onPressed: () {}, child: null, ), ), ), ], ); } }
flutter/examples/api/lib/widgets/basic/absorb_pointer.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/basic/absorb_pointer.0.dart", "repo_id": "flutter", "token_count": 654 }
625
// 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 [MouseRegion.onExit]. void main() => runApp(const MouseRegionApp()); class MouseRegionApp extends StatelessWidget { const MouseRegionApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('MouseRegion.onExit Sample')), body: const Center( child: MouseRegionExample(), ), ), ); } } class MouseRegionExample extends StatefulWidget { const MouseRegionExample({super.key}); @override State<MouseRegionExample> createState() => _MouseRegionExampleState(); } class _MouseRegionExampleState extends State<MouseRegionExample> { bool hovered = false; @override Widget build(BuildContext context) { return Container( height: 100, width: 100, decoration: BoxDecoration(color: hovered ? Colors.yellow : Colors.blue), child: MouseRegion( onEnter: (_) { setState(() { hovered = true; }); }, onExit: (_) { setState(() { hovered = false; }); }, ), ); } }
flutter/examples/api/lib/widgets/basic/mouse_region.on_exit.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/basic/mouse_region.on_exit.0.dart", "repo_id": "flutter", "token_count": 523 }
626
// 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 [Focus]. void main() => runApp(const FocusExampleApp()); class FocusExampleApp extends StatelessWidget { const FocusExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Focus Sample')), body: const FocusExample(), ), ); } } class FocusExample extends StatefulWidget { const FocusExample({super.key}); @override State<FocusExample> createState() => _FocusExampleState(); } class _FocusExampleState extends State<FocusExample> { Color _color = Colors.white; KeyEventResult _handleKeyPress(FocusNode node, KeyEvent event) { if (event is KeyDownEvent) { debugPrint('Focus node ${node.debugLabel} got key event: ${event.logicalKey}'); switch (event.logicalKey) { case LogicalKeyboardKey.keyR: debugPrint('Changing color to red.'); setState(() { _color = Colors.red; }); return KeyEventResult.handled; case LogicalKeyboardKey.keyG: debugPrint('Changing color to green.'); setState(() { _color = Colors.green; }); return KeyEventResult.handled; case LogicalKeyboardKey.keyB: debugPrint('Changing color to blue.'); setState(() { _color = Colors.blue; }); return KeyEventResult.handled; } } return KeyEventResult.ignored; } @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; return FocusScope( debugLabel: 'Scope', autofocus: true, child: DefaultTextStyle( style: textTheme.headlineMedium!, child: Focus( onKeyEvent: _handleKeyPress, debugLabel: 'Button', child: Builder( builder: (BuildContext context) { final FocusNode focusNode = Focus.of(context); final bool hasFocus = focusNode.hasFocus; return GestureDetector( onTap: () { if (hasFocus) { focusNode.unfocus(); } else { focusNode.requestFocus(); } }, child: Center( child: Container( width: 400, height: 100, alignment: Alignment.center, color: hasFocus ? _color : Colors.white, child: Text(hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'), ), ), ); }, ), ), ), ); } }
flutter/examples/api/lib/widgets/focus_scope/focus.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/focus_scope/focus.0.dart", "repo_id": "flutter", "token_count": 1304 }
627
// 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 [Image.errorBuilder]. void main() => runApp(const ErrorBuilderExampleApp()); class ErrorBuilderExampleApp extends StatelessWidget { const ErrorBuilderExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: ErrorBuilderExample(), ), ), ); } } class ErrorBuilderExample extends StatelessWidget { const ErrorBuilderExample({super.key}); @override Widget build(BuildContext context) { return DecoratedBox( decoration: BoxDecoration( color: Colors.white, border: Border.all(), borderRadius: BorderRadius.circular(20), ), child: Image.network( 'https://example.does.not.exist/image.jpg', errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { // Appropriate logging or analytics, e.g. // myAnalytics.recordError( // 'An error occurred loading "https://example.does.not.exist/image.jpg"', // exception, // stackTrace, // ); return const Text('😢'); }, ), ); } }
flutter/examples/api/lib/widgets/image/image.error_builder.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/image/image.error_builder.0.dart", "repo_id": "flutter", "token_count": 538 }
628
// 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 [InteractiveViewer.transformationController]. void main() => runApp(const TransformationControllerExampleApp()); class TransformationControllerExampleApp extends StatelessWidget { const TransformationControllerExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: TransformationControllerExample(), ); } } class TransformationControllerExample extends StatefulWidget { const TransformationControllerExample({super.key}); @override State<TransformationControllerExample> createState() => _TransformationControllerExampleState(); } /// [AnimationController]s can be created with `vsync: this` because of /// [TickerProviderStateMixin]. class _TransformationControllerExampleState extends State<TransformationControllerExample> with TickerProviderStateMixin { final TransformationController _transformationController = TransformationController(); Animation<Matrix4>? _animationReset; late final AnimationController _controllerReset; void _onAnimateReset() { _transformationController.value = _animationReset!.value; if (!_controllerReset.isAnimating) { _animationReset!.removeListener(_onAnimateReset); _animationReset = null; _controllerReset.reset(); } } void _animateResetInitialize() { _controllerReset.reset(); _animationReset = Matrix4Tween( begin: _transformationController.value, end: Matrix4.identity(), ).animate(_controllerReset); _animationReset!.addListener(_onAnimateReset); _controllerReset.forward(); } // Stop a running reset to home transform animation. void _animateResetStop() { _controllerReset.stop(); _animationReset?.removeListener(_onAnimateReset); _animationReset = null; _controllerReset.reset(); } void _onInteractionStart(ScaleStartDetails details) { // If the user tries to cause a transformation while the reset animation is // running, cancel the reset animation. if (_controllerReset.status == AnimationStatus.forward) { _animateResetStop(); } } @override void initState() { super.initState(); _controllerReset = AnimationController( vsync: this, duration: const Duration(milliseconds: 400), ); } @override void dispose() { _controllerReset.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).colorScheme.primary, appBar: AppBar( automaticallyImplyLeading: false, title: const Text('Controller demo'), ), body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: _transformationController, minScale: 0.1, maxScale: 1.0, onInteractionStart: _onInteractionStart, child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: <Color>[Colors.orange, Colors.red], stops: <double>[0.0, 1.0], ), ), ), ), ), persistentFooterButtons: <Widget>[ IconButton( onPressed: _animateResetInitialize, tooltip: 'Reset', color: Theme.of(context).colorScheme.surface, icon: const Icon(Icons.replay), ), ], ); } }
flutter/examples/api/lib/widgets/interactive_viewer/interactive_viewer.transformation_controller.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/interactive_viewer/interactive_viewer.transformation_controller.0.dart", "repo_id": "flutter", "token_count": 1351 }
629
// 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 [NestedScrollView]. void main() => runApp(const NestedScrollViewExampleApp()); class NestedScrollViewExampleApp extends StatelessWidget { const NestedScrollViewExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: NestedScrollViewExample(), ); } } class NestedScrollViewExample extends StatelessWidget { const NestedScrollViewExample({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: NestedScrollView(headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar( title: const Text('Snapping Nested SliverAppBar'), floating: true, snap: true, expandedHeight: 200.0, forceElevated: innerBoxIsScrolled, ), ), ]; }, body: Builder(builder: (BuildContext context) { return CustomScrollView( // The "controller" and "primary" members should be left unset, so that // the NestedScrollView can control this inner scroll view. // If the "controller" property is set, then this scroll view will not // be associated with the NestedScrollView. slivers: <Widget>[ SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), SliverFixedExtentList( itemExtent: 48.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => ListTile(title: Text('Item $index')), childCount: 30, ), ), ], ); }))); } }
flutter/examples/api/lib/widgets/nested_scroll_view/nested_scroll_view.2.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/nested_scroll_view/nested_scroll_view.2.dart", "repo_id": "flutter", "token_count": 779 }
630
// 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 [RouteObserver]. final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>(); void main() { runApp(const RouteObserverApp()); } class RouteObserverApp extends StatelessWidget { const RouteObserverApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( navigatorObservers: <NavigatorObserver>[ routeObserver ], home: const RouteObserverExample(), ); } } class RouteObserverExample extends StatefulWidget { const RouteObserverExample({super.key}); @override State<RouteObserverExample> createState() => _RouteObserverExampleState(); } class _RouteObserverExampleState extends State<RouteObserverExample> with RouteAware { List<String> log = <String>[]; @override void didChangeDependencies() { super.didChangeDependencies(); routeObserver.subscribe(this, ModalRoute.of(context)!); } @override void dispose() { routeObserver.unsubscribe(this); super.dispose(); } @override void didPush() { // Route was pushed onto navigator and is now the topmost route. log.add('didPush'); } @override void didPopNext() { // Covering route was popped off the navigator. log.add('didPopNext'); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( 'RouteObserver log:', style: Theme.of(context).textTheme.headlineSmall, ), ConstrainedBox( constraints: const BoxConstraints(maxHeight: 300.0), child: ListView.builder( itemCount: log.length, itemBuilder: (BuildContext context, int index) { if (log.isEmpty) { return const SizedBox.shrink(); } return Text( log[index], textAlign: TextAlign.center, ); }, ), ), OutlinedButton( onPressed: () { Navigator.of(context).push<void>( MaterialPageRoute<void>( builder: (BuildContext context) => const NextPage(), ), ); }, child: const Text('Go to next page'), ), ], ), ), ); } } class NextPage extends StatelessWidget { const NextPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FilledButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Go back to RouteAware page'), ) ), ); } }
flutter/examples/api/lib/widgets/routes/route_observer.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/routes/route_observer.0.dart", "repo_id": "flutter", "token_count": 1373 }
631
// 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'; /// Flutter code sample for [SharedAppData]. // A single lazily-constructed object that's shared with the entire application // via `SharedObject.of(context)`. The value of the object can be changed with // `SharedObject.reset(context)`. Resetting the value will cause all of the // widgets that depend on it to be rebuilt. class SharedObject { SharedObject._(); static final Object _sharedObjectKey = Object(); @override String toString() => describeIdentity(this); static void reset(BuildContext context) { // Calling SharedAppData.setValue() causes dependent widgets to be rebuilt. SharedAppData.setValue<Object, SharedObject>(context, _sharedObjectKey, SharedObject._()); } static SharedObject of(BuildContext context) { // If a value for _sharedObjectKey has never been set then the third // callback parameter is used to generate an initial value. return SharedAppData.getValue<Object, SharedObject>(context, _sharedObjectKey, () => SharedObject._()); } } // An example of a widget which depends on the SharedObject's value, which might // be provided - along with SharedObject - in a Dart package. class CustomWidget extends StatelessWidget { const CustomWidget({super.key}); @override Widget build(BuildContext context) { // Will be rebuilt if the shared object's value is changed. return ElevatedButton( child: Text('Replace ${SharedObject.of(context)}'), onPressed: () { SharedObject.reset(context); }, ); } } class Home extends StatelessWidget { const Home({super.key}); @override Widget build(BuildContext context) { return const Scaffold( body: Center(child: CustomWidget()), ); } } void main() { runApp(const MaterialApp(home: Home())); }
flutter/examples/api/lib/widgets/shared_app_data/shared_app_data.1.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/shared_app_data/shared_app_data.1.dart", "repo_id": "flutter", "token_count": 587 }
632
// 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'; /// Flutter code sample for a [ChangeNotifier] with a [ListenableBuilder]. void main() { runApp(const ListenableBuilderExample()); } class ListModel with ChangeNotifier { final List<int> _values = <int>[]; List<int> get values => _values.toList(); // O(N), makes a new copy each time. void add(int value) { _values.add(value); notifyListeners(); } } class ListenableBuilderExample extends StatefulWidget { const ListenableBuilderExample({super.key}); @override State<ListenableBuilderExample> createState() => _ListenableBuilderExampleState(); } class _ListenableBuilderExampleState extends State<ListenableBuilderExample> { final ListModel _listNotifier = ListModel(); final math.Random _random = math.Random(0); // fixed seed for reproducibility @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('ListenableBuilder Example')), body: ListBody(listNotifier: _listNotifier), floatingActionButton: FloatingActionButton( onPressed: () => _listNotifier.add(_random.nextInt(1 << 31)), // 1 << 31 is the maximum supported value child: const Icon(Icons.add), ), ), ); } } class ListBody extends StatelessWidget { const ListBody({super.key, required this.listNotifier}); final ListModel listNotifier; @override Widget build(BuildContext context) { return Center( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ const Text('Current values:'), Expanded( child: ListenableBuilder( listenable: listNotifier, builder: (BuildContext context, Widget? child) { // We rebuild the ListView each time the list changes, // so that the framework knows to update the rendering. final List<int> values = listNotifier.values; // copy the list return ListView.builder( itemBuilder: (BuildContext context, int index) => ListTile( title: Text('${values[index]}'), ), itemCount: values.length, ); }, ), ), ], ), ); } }
flutter/examples/api/lib/widgets/transitions/listenable_builder.3.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/transitions/listenable_builder.3.dart", "repo_id": "flutter", "token_count": 980 }
633
// 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_api_samples/cupertino/button/cupertino_button.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Has 4 CupertinoButton variants', (WidgetTester tester) async { await tester.pumpWidget( const example.CupertinoButtonApp(), ); expect(find.byType(CupertinoButton), findsNWidgets(4)); expect(find.ancestor(of: find.text('Enabled'), matching: find.byType(CupertinoButton)), findsNWidgets(2)); expect(find.ancestor(of: find.text('Disabled'), matching: find.byType(CupertinoButton)), findsNWidgets(2)); }); }
flutter/examples/api/test/cupertino/button/cupertino_button.0_test.dart/0
{ "file_path": "flutter/examples/api/test/cupertino/button/cupertino_button.0_test.dart", "repo_id": "flutter", "token_count": 277 }
634
// 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_api_samples/cupertino/refresh/cupertino_sliver_refresh_control.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can pull down to reveal CupertinoSliverRefreshControl', (WidgetTester tester) async { await tester.pumpWidget( const example.RefreshControlApp(), ); expect(find.byType(CupertinoSliverRefreshControl), findsNothing); expect(find.byType(Container), findsNWidgets(3)); final Finder firstItem = find.byType(Container).first; await tester.drag(firstItem, const Offset(0.0, 150.0), touchSlopY: 0); await tester.pump(); expect(find.byType(CupertinoSliverRefreshControl), findsOneWidget); await tester.pumpAndSettle(); expect(find.byType(CupertinoSliverRefreshControl), findsNothing); expect(find.byType(Container), findsNWidgets(4)); }); }
flutter/examples/api/test/cupertino/refresh/cupertino_sliver_refresh_control.0_test.dart/0
{ "file_path": "flutter/examples/api/test/cupertino/refresh/cupertino_sliver_refresh_control.0_test.dart", "repo_id": "flutter", "token_count": 373 }
635
// 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/gestures/tap_and_drag/tap_and_drag.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Single tap + drag should not change the scale of child', (WidgetTester tester) async { await tester.pumpWidget( const example.TapAndDragToZoomApp(), ); double getScale() { final RenderBox box = tester.renderObject(find.byType(Container).first); return box.getTransformTo(null)[0]; } final Finder containerFinder = find.byType(Container).first; final Offset centerOfChild = tester.getCenter(containerFinder); expect(getScale(), 1.0); // Single tap + drag down. final TestGesture gesture = await tester.startGesture(centerOfChild); await tester.pump(); await gesture.moveTo(centerOfChild + const Offset(0, 100.0)); await tester.pump(); expect(getScale(), 1.0); // Single tap + drag up. await gesture.moveTo(centerOfChild); await tester.pump(); expect(getScale(), 1.0); }); testWidgets('Double tap + drag should change the scale of the child', (WidgetTester tester) async { await tester.pumpWidget( const example.TapAndDragToZoomApp(), ); double getScale() { final RenderBox box = tester.renderObject(find.byType(Container).first); return box.getTransformTo(null)[0]; } final Finder containerFinder = find.byType(Container).first; final Offset centerOfChild = tester.getCenter(containerFinder); expect(getScale(), 1.0); // Double tap + drag down to scale up. final TestGesture gesture = await tester.startGesture(centerOfChild); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(centerOfChild); await tester.pump(); await gesture.moveTo(centerOfChild + const Offset(0, 100.0)); await tester.pump(); expect(getScale(), greaterThan(1.0)); // Scale is reset on drag end. await gesture.up(); await tester.pumpAndSettle(); expect(getScale(), 1.0); // Double tap + drag up to scale down. await gesture.down(centerOfChild); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(centerOfChild); await tester.pump(); await gesture.moveTo(centerOfChild + const Offset(0, -100.0)); await tester.pump(); expect(getScale(), lessThan(1.0)); // Scale is reset on drag end. await gesture.up(); await tester.pumpAndSettle(); expect(getScale(), 1.0); }); }
flutter/examples/api/test/gestures/tap_and_drag/tap_and_drag.0_test.dart/0
{ "file_path": "flutter/examples/api/test/gestures/tap_and_drag/tap_and_drag.0_test.dart", "repo_id": "flutter", "token_count": 992 }
636
// 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/autocomplete/autocomplete.2.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('can search and find options after waiting for fake network delay', (WidgetTester tester) async { await tester.pumpWidget(const example.AutocompleteExampleApp()); expect(find.text('aardvark'), findsNothing); expect(find.text('bobcat'), findsNothing); expect(find.text('chameleon'), findsNothing); await tester.enterText(find.byType(TextFormField), 'a'); await tester.pump(example.fakeAPIDuration); expect(find.text('aardvark'), findsOneWidget); expect(find.text('bobcat'), findsOneWidget); expect(find.text('chameleon'), findsOneWidget); await tester.enterText(find.byType(TextFormField), 'aa'); await tester.pump(example.fakeAPIDuration); expect(find.text('aardvark'), findsOneWidget); expect(find.text('bobcat'), findsNothing); expect(find.text('chameleon'), findsNothing); }); }
flutter/examples/api/test/material/autocomplete/autocomplete.2_test.dart/0
{ "file_path": "flutter/examples/api/test/material/autocomplete/autocomplete.2_test.dart", "repo_id": "flutter", "token_count": 406 }
637
// 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/checkbox_list_tile/custom_labeled_checkbox.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('LinkedLabelCheckbox contains RichText and Checkbox', (WidgetTester tester) async { await tester.pumpWidget( const example.LabeledCheckboxApp(), ); // Label text is in a RichText widget with the correct text. final RichText richText = tester.widget(find.byType(RichText).first); expect(richText.text.toPlainText(), 'Linked, tappable label text'); // Checkbox is initially unchecked. Checkbox checkbox = tester.widget(find.byType(Checkbox)); expect(checkbox.value, isFalse); // Tap the checkbox to check it. await tester.tap(find.byType(Checkbox)); await tester.pumpAndSettle(); // Checkbox is now checked. checkbox = tester.widget(find.byType(Checkbox)); expect(checkbox.value, isTrue); }); }
flutter/examples/api/test/material/checkbox_list_tile/custom_labeled_checkbox.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/checkbox_list_tile/custom_labeled_checkbox.0_test.dart", "repo_id": "flutter", "token_count": 388 }
638
// 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/adaptive_alert_dialog.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Show Adaptive Alert dialog', (WidgetTester tester) async { const String dialogTitle = 'AlertDialog Title'; await tester.pumpWidget( const MaterialApp( home: Scaffold( body: example.AdaptiveAlertDialogApp(), ), ), ); expect(find.text(dialogTitle), findsNothing); await tester.tap(find.widgetWithText(TextButton, 'Show Dialog')); await tester.pumpAndSettle(); expect(find.text(dialogTitle), findsOneWidget); await tester.tap(find.text('OK')); await tester.pumpAndSettle(); expect(find.text(dialogTitle), findsNothing); }); }
flutter/examples/api/test/material/dialog/adaptive_alert_dialog.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/dialog/adaptive_alert_dialog.0_test.dart", "repo_id": "flutter", "token_count": 353 }
639
// 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/dropdown_menu/dropdown_menu_entry_label_widget.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('DropdownEntryLabelWidget appears', (WidgetTester tester) async { await tester.pumpWidget( const example.DropdownMenuEntryLabelWidgetExampleApp(), ); const String longText = 'is a color that sings of hope, A hue that shines like gold. It is the color of dreams, A shade that never grows old.'; Finder findMenuItemText(String label) { final String labelText = '$label $longText\n'; return find.descendant( of: find.widgetWithText(MenuItemButton, labelText), matching: find.byType(Text), ).last; } // Open the menu await tester.tap(find.byType(TextField)); expect(findMenuItemText('Blue'), findsOneWidget); expect(findMenuItemText('Pink'), findsOneWidget); expect(findMenuItemText('Green'), findsOneWidget); expect(findMenuItemText('Yellow'), findsOneWidget); expect(findMenuItemText('Grey'), findsOneWidget); // Close the menu await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); }); }
flutter/examples/api/test/material/dropdown_menu/dropdown_menu_entry_label_widget.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/dropdown_menu/dropdown_menu_entry_label_widget.0_test.dart", "repo_id": "flutter", "token_count": 472 }
640
// 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/ink_well/ink_well.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Clicking on InkWell changes the Size of 50x50 AnimatedContainer to 100x100 and vice versa', (WidgetTester tester) async { await tester.pumpWidget( const example.InkWellExampleApp(), ); expect(find.widgetWithText(AppBar, 'InkWell Sample'), findsOneWidget); final Finder inkWell = find.byType(InkWell); final InkWell inkWellWidget = tester.widget<InkWell>(inkWell); final Finder animatedContainer = find.byType(AnimatedContainer); AnimatedContainer animatedContainerWidget = tester.widget<AnimatedContainer>(animatedContainer); expect(inkWell, findsOneWidget); expect(inkWellWidget.onTap.runtimeType, VoidCallback); expect(animatedContainerWidget.constraints?.minWidth, 50); expect(animatedContainerWidget.constraints?.minHeight, 50); await tester.tap(inkWell); await tester.pumpAndSettle(); animatedContainerWidget = tester.widget<AnimatedContainer>(animatedContainer); expect(animatedContainerWidget.constraints?.minWidth, 100); expect(animatedContainerWidget.constraints?.minHeight, 100); await tester.tap(inkWell); await tester.pumpAndSettle(); animatedContainerWidget = tester.widget<AnimatedContainer>(animatedContainer); expect(animatedContainerWidget.constraints?.minWidth, 50); expect(animatedContainerWidget.constraints?.minHeight, 50); }); }
flutter/examples/api/test/material/ink_well/ink_well.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/ink_well/ink_well.0_test.dart", "repo_id": "flutter", "token_count": 546 }
641
// 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/menu_anchor/checkbox_menu_button.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can open menu and show message', (WidgetTester tester) async { await tester.pumpWidget( const example.MenuApp(), ); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); expect(find.text('Show Message'), findsOneWidget); expect(find.text(example.MenuApp.kMessage), findsNothing); await tester.tap(find.text('Show Message')); await tester.pumpAndSettle(); expect(find.text('Show Message'), findsNothing); expect(find.text(example.MenuApp.kMessage), findsOneWidget); }); testWidgets('MenuAnchor 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.MenuApp(), ), ); expect(tester.getTopLeft(find.byType(MenuAnchor)), const Offset(0.0, safeAreaPadding)); }); }
flutter/examples/api/test/material/menu_anchor/checkbox_menu_button.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/menu_anchor/checkbox_menu_button.0_test.dart", "repo_id": "flutter", "token_count": 492 }
642
// 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/paginated_data_table/paginated_data_table.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('PaginatedDataTable 1', (WidgetTester tester) async { await tester.pumpWidget(const example.DataTableExampleApp()); expect(find.text('Strange New Worlds'), findsOneWidget); await tester.tap(find.byIcon(Icons.arrow_upward).at(1)); await tester.pump(); expect(find.text('Strange New Worlds'), findsNothing); await tester.tap(find.byIcon(Icons.chevron_right)); await tester.pump(); expect(find.text('Strange New Worlds'), findsOneWidget); await tester.tap(find.byIcon(Icons.arrow_upward).at(1)); await tester.pump(); expect(find.text('Strange New Worlds'), findsNothing); }); }
flutter/examples/api/test/material/paginated_data_table/paginated_data_table.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/paginated_data_table/paginated_data_table.1_test.dart", "repo_id": "flutter", "token_count": 346 }
643
// 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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/reorderable_list/reorderable_list_view.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Content is reordered after a drag', (WidgetTester tester) async { await tester.pumpWidget( const example.ReorderableApp(), ); bool item1IsBeforeItem2() { final Iterable<Text> texts = tester.widgetList<Text>(find.byType(Text)); final List<String?> labels = texts.map((final Text text) => text.data).toList(); return labels.indexOf('Item 1') < labels.indexOf('Item 2'); } expect(item1IsBeforeItem2(), true); // Drag 'Item 1' after 'Item 4'. final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 1'))); await tester.pump(kLongPressTimeout + kPressTimeout); await tester.pumpAndSettle(); await drag.moveTo(tester.getCenter(find.text('Item 4'))); await drag.up(); await tester.pumpAndSettle(); expect(item1IsBeforeItem2(), false); }); }
flutter/examples/api/test/material/reorderable_list/reorderable_list_view.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/reorderable_list/reorderable_list_view.0_test.dart", "repo_id": "flutter", "token_count": 453 }
644
// 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/stepper/step_style.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('StepStyle Smoke Test', (WidgetTester tester) async { await tester.pumpWidget( const example.StepStyleExampleApp(), ); expect(find.widgetWithText(AppBar, 'Step Style Example'), findsOneWidget); final Stepper stepper = tester.widget<Stepper>(find.byType(Stepper)); // Check that the stepper has the correct properties. expect(stepper.type, StepperType.horizontal); expect(stepper.stepIconHeight, 48); expect(stepper.stepIconWidth, 48); expect(stepper.stepIconMargin, EdgeInsets.zero); // Check that the first step has the correct properties. final Step firstStep = stepper.steps[0]; expect(firstStep.title, isA<SizedBox>()); expect(firstStep.content, isA<SizedBox>()); expect(firstStep.isActive, true); expect(firstStep.stepStyle?.connectorThickness, 10); expect(firstStep.stepStyle?.color, Colors.white); expect(firstStep.stepStyle?.connectorColor, Colors.red); expect(firstStep.stepStyle?.indexStyle?.color, Colors.black); expect(firstStep.stepStyle?.indexStyle?.fontSize, 20); expect(firstStep.stepStyle?.border, Border.all(width: 2)); // Check that the second step has the correct properties. final Step secondStep = stepper.steps[1]; expect(secondStep.title, isA<SizedBox>()); expect(secondStep.content, isA<SizedBox>()); expect(secondStep.isActive, true); expect(secondStep.stepStyle?.connectorThickness, 10); expect(secondStep.stepStyle?.connectorColor, Colors.orange); expect(secondStep.stepStyle?.gradient, const LinearGradient( colors: <Color>[ Colors.white, Colors.black, ], )); // Check that the third step has the correct properties. final Step thirdStep = stepper.steps[2]; expect(thirdStep.title, isA<SizedBox>()); expect(thirdStep.content, isA<SizedBox>()); expect(thirdStep.isActive, true); expect(thirdStep.stepStyle?.connectorThickness, 10); expect(thirdStep.stepStyle?.color, Colors.white); expect(thirdStep.stepStyle?.connectorColor, Colors.blue); expect(thirdStep.stepStyle?.indexStyle?.color, Colors.black); expect(thirdStep.stepStyle?.indexStyle?.fontSize, 20); expect(thirdStep.stepStyle?.border, Border.all(width: 2)); // Check that the fourth step has the correct properties. final Step fourthStep = stepper.steps[3]; expect(fourthStep.title, isA<SizedBox>()); expect(fourthStep.content, isA<SizedBox>()); expect(fourthStep.isActive, true); expect(fourthStep.stepStyle?.color, Colors.white); expect(fourthStep.stepStyle?.indexStyle?.color, Colors.black); expect(fourthStep.stepStyle?.indexStyle?.fontSize, 20); expect(fourthStep.stepStyle?.border, Border.all(width: 2)); }); }
flutter/examples/api/test/material/stepper/step_style.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/stepper/step_style.0_test.dart", "repo_id": "flutter", "token_count": 1109 }
645
// 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/text_field/text_field.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('TextField is obscured and has "Password" as labelText', (WidgetTester tester) async { await tester.pumpWidget(const example.TextFieldExampleApp()); expect(find.byType(TextField), findsOneWidget); final TextField textField = tester.widget<TextField>(find.byType(TextField)); expect(textField.obscureText, isTrue); expect(textField.decoration!.labelText, 'Password'); }); }
flutter/examples/api/test/material/text_field/text_field.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/text_field/text_field.0_test.dart", "repo_id": "flutter", "token_count": 243 }
646
// 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/rendering/scroll_direction/scroll_direction.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Example app has ScrollDirection represented', (WidgetTester tester) async { await tester.pumpWidget( const example.ExampleApp(), ); expect(find.byType(Radio<AxisDirection>), findsNWidgets(4)); final RenderViewport viewport = tester.renderObject(find.byType(Viewport)); expect(find.text('AxisDirection.down'), findsOneWidget); expect(find.text('Axis.vertical'), findsOneWidget); expect(find.text('GrowthDirection.forward'), findsOneWidget); expect(find.text('ScrollDirection.idle'), findsOneWidget); expect(find.byIcon(Icons.arrow_downward_rounded), findsNWidgets(2)); expect(viewport.axisDirection, AxisDirection.down); await tester.tap( find.byWidgetPredicate((Widget widget) { return widget is Radio<AxisDirection> && widget.value == AxisDirection.up; }) ); await tester.pumpAndSettle(); expect(find.text('AxisDirection.up'), findsOneWidget); expect(find.text('Axis.vertical'), findsOneWidget); expect(find.text('GrowthDirection.forward'), findsOneWidget); expect(find.text('ScrollDirection.idle'), findsOneWidget); expect(find.byIcon(Icons.arrow_upward_rounded), findsNWidgets(2)); expect(viewport.axisDirection, AxisDirection.up); }); }
flutter/examples/api/test/rendering/scroll_direction.0_test.dart/0
{ "file_path": "flutter/examples/api/test/rendering/scroll_direction.0_test.dart", "repo_id": "flutter", "token_count": 582 }
647
// 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/clip_rrect.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ClipRRect adds rounded corners to containers', (WidgetTester tester) async { await tester.pumpWidget( const example.ClipRRectApp(), ); final Finder clipRRectFinder = find.byType(ClipRRect); final Finder containerFinder = find.byType(Container); expect(clipRRectFinder, findsNWidgets(2)); expect(containerFinder, findsNWidgets(3)); final Rect firstClipRect = tester.getRect(clipRRectFinder.first); final Rect secondContainerRect = tester.getRect(containerFinder.at(1)); expect(firstClipRect, equals(secondContainerRect)); final Rect secondClipRect = tester.getRect(clipRRectFinder.at(1)); final Rect thirdContainerRect = tester.getRect(containerFinder.at(2)); expect(secondClipRect, equals(thirdContainerRect)); }); }
flutter/examples/api/test/widgets/basic/clip_rrect.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/basic/clip_rrect.0_test.dart", "repo_id": "flutter", "token_count": 382 }
648
// 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/physical_shape.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('PhysicalShape is an ancestor of the text widget', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp(home: example.PhysicalShapeApp()), ); final PhysicalShape physicalShape = tester.widget<PhysicalShape>( find.ancestor( of:find.text('Hello, World!'), matching: find.byType(PhysicalShape), ), ); expect(physicalShape.clipper, isNotNull); expect(physicalShape.color, Colors.orange); expect(physicalShape.elevation, 5.0); }); }
flutter/examples/api/test/widgets/basic/physical_shape.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/basic/physical_shape.0_test.dart", "repo_id": "flutter", "token_count": 303 }
649
// 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/widgets/navigator_pop_handler/navigator_pop_handler.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; import '../navigator_utils.dart'; void main() { testWidgets('Can go back with system back gesture', (WidgetTester tester) async { await tester.pumpWidget( const example.NavigatorPopHandlerApp(), ); expect(find.text('Nested Navigators Example'), findsOneWidget); expect(find.text('Nested Navigators Page One'), findsNothing); expect(find.text('Nested Navigators Page Two'), findsNothing); await tester.tap(find.text('Nested Navigator route')); await tester.pumpAndSettle(); expect(find.text('Nested Navigators Example'), findsNothing); expect(find.text('Nested Navigators Page One'), findsOneWidget); expect(find.text('Nested Navigators Page Two'), findsNothing); await tester.tap(find.text('Go to another route in this nested Navigator')); await tester.pumpAndSettle(); expect(find.text('Nested Navigators Example'), findsNothing); expect(find.text('Nested Navigators Page One'), findsNothing); expect(find.text('Nested Navigators Page Two'), findsOneWidget); await simulateSystemBack(); await tester.pumpAndSettle(); expect(find.text('Nested Navigators Example'), findsNothing); expect(find.text('Nested Navigators Page One'), findsOneWidget); expect(find.text('Nested Navigators Page Two'), findsNothing); await simulateSystemBack(); await tester.pumpAndSettle(); expect(find.text('Nested Navigators Example'), findsOneWidget); expect(find.text('Nested Navigators Page One'), findsNothing); expect(find.text('Nested Navigators Page Two'), findsNothing); }); }
flutter/examples/api/test/widgets/navigator_pop_handler/navigator_pop_handler.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/navigator_pop_handler/navigator_pop_handler.0_test.dart", "repo_id": "flutter", "token_count": 598 }
650
// 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/scroll_view/list_view.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( 'tapping Reverse button should reverse ListView', (WidgetTester tester) async { await tester.pumpWidget(const example.ListViewExampleApp()); final Finder listView = find.byType(ListView); final Finder reverseFinder = find.text('Reverse items'); expect(listView, findsOneWidget); expect(reverseFinder, findsOneWidget); final Finder keepAliveItemFinder = find.byType(example.KeepAliveItem); example.KeepAliveItem firstWidget = tester.firstWidget(keepAliveItemFinder); expect(firstWidget.data, '1'); await tester.tap(reverseFinder); await tester.pump(); firstWidget = tester.firstWidget(keepAliveItemFinder); expect(firstWidget.data, '5'); }, ); }
flutter/examples/api/test/widgets/scroll_view/list_view.1_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/scroll_view/list_view.1_test.dart", "repo_id": "flutter", "token_count": 390 }
651
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="21208.1" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21208.1"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--Flutter View Controller--> <scene sceneID="MPq-6h-HP0"> <objects> <viewController id="7GY-dJ-cew" userLabel="Flutter View Controller" customClass="FlutterViewController" sceneMemberID="viewController"> <view key="view" id="eEt-A6-Jxk"> <rect key="frame" x="0.0" y="0.0" width="450" height="404"/> <autoresizingMask key="autoresizingMask"/> </view> </viewController> <customObject id="eTc-YD-UwH" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="287" y="704"/> </scene> <!--Main View Controller--> <scene sceneID="OoP-iw-RGx"> <objects> <viewController storyboardIdentifier="MainViewController" id="Zco-B0-Eo5" customClass="MainViewController" customModule="flutter_view" customModuleProvider="target" sceneMemberID="viewController"> <view key="view" id="yo2-24-9SJ"> <rect key="frame" x="0.0" y="0.0" width="913" height="683"/> <autoresizingMask key="autoresizingMask"/> <subviews> <stackView distribution="fill" orientation="horizontal" alignment="top" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="vIi-fL-74a"> <rect key="frame" x="0.0" y="0.0" width="913" height="683"/> <subviews> <containerView translatesAutoresizingMaskIntoConstraints="NO" id="NLg-mU-To9"> <rect key="frame" x="0.0" y="1" width="450" height="682"/> <connections> <segue destination="fkR-dw-CPc" kind="embed" identifier="NativeViewControllerSegue" id="JOW-cD-XX0"/> </connections> </containerView> <containerView translatesAutoresizingMaskIntoConstraints="NO" id="AGJ-Cf-BSz"> <rect key="frame" x="458" y="1" width="455" height="682"/> <connections> <segue destination="7GY-dJ-cew" kind="embed" identifier="FlutterViewControllerSegue" id="0Il-tC-ptk"/> </connections> </containerView> </subviews> <constraints> <constraint firstItem="AGJ-Cf-BSz" firstAttribute="height" secondItem="NLg-mU-To9" secondAttribute="height" id="5bU-7q-KyD"/> <constraint firstItem="AGJ-Cf-BSz" firstAttribute="width" secondItem="NLg-mU-To9" secondAttribute="width" multiplier="1.01111" id="PQE-oI-RoL"/> </constraints> <visibilityPriorities> <integer value="1000"/> <integer value="1000"/> </visibilityPriorities> <customSpacing> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> </customSpacing> </stackView> </subviews> <constraints> <constraint firstAttribute="bottom" secondItem="vIi-fL-74a" secondAttribute="bottom" id="ORj-Up-bVE"/> <constraint firstAttribute="trailing" secondItem="vIi-fL-74a" secondAttribute="trailing" id="XqL-pC-rc8"/> <constraint firstItem="vIi-fL-74a" firstAttribute="leading" secondItem="yo2-24-9SJ" secondAttribute="leading" id="kXT-6f-V55"/> <constraint firstItem="vIi-fL-74a" firstAttribute="top" secondItem="yo2-24-9SJ" secondAttribute="top" id="ws7-M4-M5U"/> </constraints> </view> </viewController> <customObject id="RER-RE-Ii7" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="13.5" y="26.5"/> </scene> <!--Native View Controller--> <scene sceneID="6te-4i-Zpy"> <objects> <viewController id="fkR-dw-CPc" userLabel="Native View Controller" customClass="NativeViewController" customModule="flutter_view" customModuleProvider="target" sceneMemberID="viewController"> <view key="view" id="lMy-hx-gLK"> <rect key="frame" x="0.0" y="0.0" width="450" height="404"/> <autoresizingMask key="autoresizingMask"/> <subviews> <stackView distribution="fillProportionally" orientation="vertical" alignment="leading" spacing="0.0" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="bEP-zh-PC4"> <rect key="frame" x="0.0" y="0.0" width="450" height="404"/> <subviews> <customView translatesAutoresizingMaskIntoConstraints="NO" id="7vK-z0-I0z" userLabel="Top"> <rect key="frame" x="0.0" y="70" width="450" height="334"/> <subviews> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="ic4-Iq-BCT"> <rect key="frame" x="207" y="163" width="4" height="16"/> <textFieldCell key="cell" lineBreakMode="clipping" id="EHZ-Ff-uN9"> <font key="font" metaFont="system" size="17"/> <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="ic4-Iq-BCT" firstAttribute="centerX" secondItem="7vK-z0-I0z" secondAttribute="centerX" id="edj-sZ-5O7"/> <constraint firstItem="ic4-Iq-BCT" firstAttribute="centerY" secondItem="7vK-z0-I0z" secondAttribute="centerY" id="v3Q-Xa-flH"/> </constraints> </customView> <customView autoresizesSubviews="NO" translatesAutoresizingMaskIntoConstraints="NO" id="O0r-UF-j95" userLabel="Bottom"> <rect key="frame" x="0.0" y="0.0" width="450" height="70"/> <subviews> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Ocn-t9-rHR"> <rect key="frame" x="18" y="20" width="100" height="35"/> <textFieldCell key="cell" lineBreakMode="clipping" title="macOS" id="TOF-2b-RIY"> <font key="font" metaFont="system" size="30"/> <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="uyM-Dx-MIG"> <rect key="frame" x="375" y="14" width="55" height="57"/> <constraints> <constraint firstAttribute="height" constant="55" id="2Zv-ge-8fE"/> <constraint firstAttribute="width" constant="55" id="bQo-k1-1eM"/> </constraints> <buttonCell key="cell" type="smallSquare" title="+" bezelStyle="smallSquare" alignment="center" lineBreakMode="truncatingTail" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="az3-aa-8jC"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system" size="18"/> </buttonCell> <connections> <action selector="handleIncrement:" target="fkR-dw-CPc" id="7k2-NW-4LI"/> </connections> </button> </subviews> <constraints> <constraint firstItem="Ocn-t9-rHR" firstAttribute="leading" secondItem="O0r-UF-j95" secondAttribute="leading" constant="20" symbolic="YES" id="KhQ-Xf-SiD"/> <constraint firstAttribute="trailing" secondItem="uyM-Dx-MIG" secondAttribute="trailing" constant="20" symbolic="YES" id="LFX-ph-6nb"/> <constraint firstAttribute="bottom" secondItem="Ocn-t9-rHR" secondAttribute="bottom" constant="20" symbolic="YES" id="Ofu-fn-RDS"/> <constraint firstAttribute="height" constant="70" id="V41-3J-PYi"/> <constraint firstAttribute="bottom" secondItem="uyM-Dx-MIG" secondAttribute="bottom" constant="15" id="Xfq-yS-emb"/> </constraints> </customView> </subviews> <visibilityPriorities> <integer value="1000"/> <integer value="1000"/> </visibilityPriorities> <customSpacing> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> </customSpacing> </stackView> </subviews> <constraints> <constraint firstItem="bEP-zh-PC4" firstAttribute="top" secondItem="lMy-hx-gLK" secondAttribute="top" id="6Fg-dO-Yhl"/> <constraint firstItem="bEP-zh-PC4" firstAttribute="leading" secondItem="lMy-hx-gLK" secondAttribute="leading" id="ZiX-CF-CPT"/> <constraint firstAttribute="bottom" secondItem="bEP-zh-PC4" secondAttribute="bottom" id="doI-ip-Pbz"/> <constraint firstAttribute="trailing" secondItem="bEP-zh-PC4" secondAttribute="trailing" id="jrN-ON-H5M"/> </constraints> </view> <connections> <outlet property="incrementLabel" destination="ic4-Iq-BCT" id="M3U-fC-vbY"/> </connections> </viewController> <customObject id="v3R-qm-QoP" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-218" y="704"/> </scene> </scenes> </document>
flutter/examples/flutter_view/macos/Main.storyboard/0
{ "file_path": "flutter/examples/flutter_view/macos/Main.storyboard", "repo_id": "flutter", "token_count": 7827 }
652
// 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 Foundation import AppKit protocol NativeViewControllerDelegate: NSObjectProtocol { func didTapIncrementButton() } /** The code behind a native view to be displayed in the `MainFlutterViewController` as an embed segue. If any storyboard view inherits from this class definition, it should contain a function to handle for `handleIncrement` */ class NativeViewController: NSViewController { var count: Int? var labelText: String { get { let count = self.count ?? 0 return "Flutter button tapped \(count) time\(count == 1 ? "" : "s")" } } var delegate: NativeViewControllerDelegate? @IBOutlet weak var incrementLabel: NSTextField! @IBAction func handleIncrement(_ sender: Any) { self.delegate?.didTapIncrementButton() } override func viewDidLoad() { super.viewDidLoad() setState(for: 0) } func didReceiveIncrement() { setState(for: (self.count ?? 0) + 1) } func setState(for count: Int) { self.count = count self.incrementLabel.stringValue = labelText } }
flutter/examples/flutter_view/macos/Runner/NativeViewController.swift/0
{ "file_path": "flutter/examples/flutter_view/macos/Runner/NativeViewController.swift", "repo_id": "flutter", "token_count": 384 }
653
#include "Generated.xcconfig"
flutter/examples/hello_world/ios/Flutter/Debug.xcconfig/0
{ "file_path": "flutter/examples/hello_world/ios/Flutter/Debug.xcconfig", "repo_id": "flutter", "token_count": 12 }
654
# This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled. version: revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 channel: unknown project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 base_revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 - platform: linux create_revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 base_revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 - platform: windows create_revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 base_revision: 5a80f8d63789494c3afb9da5434220fd2ce3d684 # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj'
flutter/examples/layers/.metadata/0
{ "file_path": "flutter/examples/layers/.metadata", "repo_id": "flutter", "token_count": 436 }
655
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
flutter/examples/layers/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "flutter/examples/layers/macos/Runner/Configs/Release.xcconfig", "repo_id": "flutter", "token_count": 32 }
656
// 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'; import 'package:flutter/rendering.dart'; /// An extension of [RenderingFlutterBinding] that owns and manages a /// [renderView]. /// /// Unlike [RenderingFlutterBinding], this binding also creates and owns a /// [renderView] to simplify bootstrapping for apps that have a dedicated main /// view. class ViewRenderingFlutterBinding extends RenderingFlutterBinding { /// Creates a binding for the rendering layer. /// /// The `root` render box is attached directly to the [renderView] and is /// given constraints that require it to fill the window. The [renderView] /// itself is attached to the [rootPipelineOwner]. /// /// This binding does not automatically schedule any frames. Callers are /// responsible for deciding when to first call [scheduleFrame]. ViewRenderingFlutterBinding({ RenderBox? root }) : _root = root; @override void initInstances() { super.initInstances(); // TODO(goderbauer): Create window if embedder doesn't provide an implicit view. assert(PlatformDispatcher.instance.implicitView != null); _renderView = initRenderView(PlatformDispatcher.instance.implicitView!); _renderView.child = _root; _root = null; } RenderBox? _root; @override RenderView get renderView => _renderView; late RenderView _renderView; /// Creates a [RenderView] object to be the root of the /// [RenderObject] rendering tree, and initializes it so that it /// will be rendered when the next frame is requested. /// /// Called automatically when the binding is created. RenderView initRenderView(FlutterView view) { final RenderView renderView = RenderView(view: view); rootPipelineOwner.rootNode = renderView; addRenderView(renderView); renderView.prepareInitialFrame(); return renderView; } @override PipelineOwner createRootPipelineOwner() { return PipelineOwner( onSemanticsOwnerCreated: () { renderView.scheduleInitialSemantics(); }, onSemanticsUpdate: (SemanticsUpdate update) { renderView.updateSemantics(update); }, onSemanticsOwnerDisposed: () { renderView.clearSemantics(); }, ); } }
flutter/examples/layers/rendering/src/binding.dart/0
{ "file_path": "flutter/examples/layers/rendering/src/binding.dart", "repo_id": "flutter", "token_count": 719 }
657
// 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/widgets.dart'; class RenderDots extends RenderConstrainedBox { RenderDots() : super(additionalConstraints: const BoxConstraints.expand()); // Makes this render box hittable so that we'll get pointer events. @override bool hitTestSelf(Offset position) => true; final Map<int, Offset> _dots = <int, Offset>{}; @override void handleEvent(PointerEvent event, BoxHitTestEntry entry) { if (event is PointerDownEvent || event is PointerMoveEvent) { _dots[event.pointer] = event.position; markNeedsPaint(); } else if (event is PointerUpEvent || event is PointerCancelEvent) { _dots.remove(event.pointer); markNeedsPaint(); } } @override void paint(PaintingContext context, Offset offset) { final Canvas canvas = context.canvas; canvas.drawRect(offset & size, Paint()..color = const Color(0xFF0000FF)); final Paint paint = Paint()..color = const Color(0xFF00FF00); for (final Offset point in _dots.values) { canvas.drawCircle(point, 50.0, paint); } super.paint(context, offset); } } class Dots extends SingleChildRenderObjectWidget { const Dots({ super.key, super.child }); @override RenderDots createRenderObject(BuildContext context) => RenderDots(); } void main() { runApp( const Directionality( textDirection: TextDirection.ltr, child: Dots( child: Center( child: Text('Touch me!'), ), ), ), ); }
flutter/examples/layers/widgets/custom_render_box.dart/0
{ "file_path": "flutter/examples/layers/widgets/custom_render_box.dart", "repo_id": "flutter", "token_count": 599 }
658
#include "Generated.xcconfig"
flutter/examples/platform_channel_swift/ios/Flutter/Release.xcconfig/0
{ "file_path": "flutter/examples/platform_channel_swift/ios/Flutter/Release.xcconfig", "repo_id": "flutter", "token_count": 12 }
659
# Example of switching between full-screen Flutter and Platform View This project demonstrates how to bring up a full-screen iOS/Android view from a full-screen Flutter view along with passing data back and forth between the two. On iOS, we use a CocoaPods dependency to add a Material Design button, and so `pod install` needs to be invoked in the `ios/` folder before `flutter run`: ``` pushd ios/ ; pod install ; popd flutter run ```
flutter/examples/platform_view/README.md/0
{ "file_path": "flutter/examples/platform_view/README.md", "repo_id": "flutter", "token_count": 119 }
660
#include "ephemeral/Flutter-Generated.xcconfig"
flutter/examples/platform_view/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "flutter/examples/platform_view/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "flutter", "token_count": 19 }
661
// 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 Cocoa /** `ViewControllers` in the xib can inherit from this class to communicate with the flutter view for this application. ViewControllers that inherit from this class should be displayed as a popover or modal, with a button that binds to the IBAction `pop()`. To get the value of the popover during close, pass a callback function as the `dispose` parameter. The callback passed will have access to the `PlatformViewController` and all of it's properties at close so that the `count` can be passed back through the message channel if needed. */ class PlatformViewController: NSViewController { var count: Int = 0 var dispose: ((PlatformViewController)->())? @IBOutlet weak var label: NSTextField! var labelText: String { get { return "Button tapped \(self.count) time\(self.count != 1 ? "s" : "")." } } override func viewDidLoad() { super.viewDidLoad() self.label.stringValue = labelText } public required init?(coder aDecoder: NSCoder) { self.count = 0 self.dispose = nil super.init(coder: aDecoder) } init(withCount count: Int, onClose dispose: ((PlatformViewController)->())?) { self.count = count self.dispose = dispose super.init(nibName: nil, bundle: nil) } @IBAction func pop(_ sender: Any) { self.dispose?(self) dismiss(self) } @IBAction func increment(_ sender: Any) { self.count += 1 self.label.stringValue = labelText } }
flutter/examples/platform_view/macos/Runner/PlatformViewController.swift/0
{ "file_path": "flutter/examples/platform_view/macos/Runner/PlatformViewController.swift", "repo_id": "flutter", "token_count": 569 }
662
@ECHO off REM Copyright 2014 The Flutter Authors. All rights reserved. REM Use of this source code is governed by a BSD-style license that can be REM found in the LICENSE file. TITLE Flutter Console echo. echo ######## ## ## ## ######## ######## ######## ######## echo ## ## ## ## ## ## ## ## ## echo ## ## ## ## ## ## ## ## ## echo ###### ## ## ## ## ## ###### ######## echo ## ## ## ## ## ## ## ## ## echo ## ## ## ## ## ## ## ## ## echo ## ######## ####### ## ## ######## ## ## echo. echo. echo WELCOME to the Flutter Console. echo =============================================================================== echo. echo Use the console below this message to interact with the "flutter" command. echo Run "flutter doctor" to check if your system is ready to run Flutter apps. echo Run "flutter create <app_name>" to create a new Flutter project. echo. echo Run "flutter help" to see all available commands. echo. echo Want to use an IDE to interact with Flutter? https://flutter.dev/ide-setup/ echo. echo Want to run the "flutter" command from any Command Prompt or PowerShell window? echo Add Flutter to your PATH: https://flutter.dev/setup-windows/#update-your-path echo. echo =============================================================================== REM "%~dp0" is the directory of this file including trailing backslash SET PATH=%~dp0bin;%PATH% CALL cmd /K "@echo off & cd %USERPROFILE% & echo on"
flutter/flutter_console.bat/0
{ "file_path": "flutter/flutter_console.bat", "repo_id": "flutter", "token_count": 655 }
663
# 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 from the Material library. * # For fixes to # * AppBar: fix_app_bar.yaml # * AppBarTheme: fix_app_bar_theme.yaml # * ColorScheme: fix_color_scheme.yaml # * SliverAppBar: fix_sliver_app_bar.yaml # * TextTheme: fix_text_theme.yaml # * ThemeData: fix_theme_data.yaml # * WidgetState: fix_widget_state.yaml version: 1 transforms: # Changes made in https://github.com/flutter/flutter/pull/15303 - title: "Replace 'child' with 'builder'" date: 2020-12-17 element: uris: [ 'material.dart' ] function: 'showDialog' changes: - kind: 'addParameter' index: 0 name: 'builder' style: optional_named argumentValue: expression: '(context) => {% widget %}' requiredIf: "widget != ''" variables: widget: kind: fragment value: 'arguments[child]' - kind: 'removeParameter' name: 'child' # Changes made in https://github.com/flutter/flutter/pull/61648 - title: "Migrate to 'autovalidateMode'" date: 2020-09-02 element: uris: [ 'material.dart' ] constructor: '' inClass: 'TextFormField' oneOf: - if: "autovalidate == 'true'" changes: - kind: 'addParameter' index: 0 name: 'autovalidateMode' style: optional_named argumentValue: expression: 'AutovalidateMode.always' requiredIf: "autovalidate == 'true'" - kind: 'removeParameter' name: 'autovalidate' - if: "autovalidate == 'false'" changes: - kind: 'addParameter' index: 0 name: 'autovalidateMode' style: optional_named argumentValue: expression: 'AutovalidateMode.disabled' requiredIf: "autovalidate == 'false'" - kind: 'removeParameter' name: 'autovalidate' variables: autovalidate: kind: 'fragment' value: 'arguments[autovalidate]' # Changes made in https://github.com/flutter/flutter/pull/61648 - title: "Migrate to 'autovalidateMode'" date: 2020-09-02 element: uris: [ 'material.dart' ] constructor: '' inClass: 'DropdownButtonFormField' oneOf: - if: "autovalidate == 'true'" changes: - kind: 'addParameter' index: 0 name: 'autovalidateMode' style: optional_named argumentValue: expression: 'AutovalidateMode.always' requiredIf: "autovalidate == 'true'" - kind: 'removeParameter' name: 'autovalidate' - if: "autovalidate == 'false'" changes: - kind: 'addParameter' index: 0 name: 'autovalidateMode' style: optional_named argumentValue: expression: 'AutovalidateMode.disabled' requiredIf: "autovalidate == 'false'" - kind: 'removeParameter' name: 'autovalidate' variables: autovalidate: kind: 'fragment' value: 'arguments[autovalidate]' # Changes made in https://github.com/flutter/flutter/pull/26259 - title: "Rename to 'resizeToAvoidBottomInset'" date: 2020-12-23 element: uris: [ 'material.dart' ] field: 'resizeToAvoidBottomPadding' inClass: 'Scaffold' changes: - kind: 'rename' newName: 'resizeToAvoidBottomInset' # Changes made in https://github.com/flutter/flutter/pull/26259 - title: "Rename to 'resizeToAvoidBottomInset'" date: 2020-12-23 element: uris: [ 'material.dart' ] constructor: '' inClass: 'Scaffold' changes: - kind: 'renameParameter' oldName: 'resizeToAvoidBottomPadding' newName: 'resizeToAvoidBottomInset' # Changes made in https://github.com/flutter/flutter/pull/68908. - title: "Migrate from 'nullOk'" date: 2021-01-27 element: uris: [ 'material.dart' ] method: 'of' inClass: 'Scaffold' oneOf: - if: "nullOk == 'true'" changes: - kind: 'rename' newName: 'maybeOf' - kind: 'removeParameter' name: 'nullOk' - if: "nullOk == 'false'" changes: - kind: 'removeParameter' name: 'nullOk' variables: nullOk: kind: 'fragment' value: 'arguments[nullOk]' # Changes made in https://github.com/flutter/flutter/pull/68908. - title: "Migrate from 'nullOk'" date: 2021-01-27 element: uris: [ 'material.dart' ] method: 'of' inClass: 'ScaffoldMessenger' oneOf: - if: "nullOk == 'true'" changes: - kind: 'rename' newName: 'maybeOf' - kind: 'removeParameter' name: 'nullOk' - if: "nullOk == 'false'" changes: - kind: 'removeParameter' name: 'nullOk' variables: nullOk: kind: 'fragment' value: 'arguments[nullOk]' # Changes made in https://github.com/flutter/flutter/pull/68905. - title: "Migrate from 'nullOk'" date: 2021-01-27 element: uris: [ 'material.dart' ] method: 'resolveFrom' inClass: 'MaterialBasedCupertinoThemeData' changes: - kind: 'removeParameter' name: 'nullOk' # Changes made in https://github.com/flutter/flutter/pull/72043 - title: "Migrate to 'maxLengthEnforcement'" date: 2020-12-13 element: uris: [ 'material.dart' ] constructor: '' inClass: 'TextFormField' oneOf: - if: "maxLengthEnforced == 'true'" changes: - kind: 'addParameter' index: 0 name: 'maxLengthEnforcement' style: optional_named argumentValue: expression: 'MaxLengthEnforcement.enforce' requiredIf: "maxLengthEnforced == 'true'" - kind: 'removeParameter' name: 'maxLengthEnforced' - if: "maxLengthEnforced == 'false'" changes: - kind: 'addParameter' index: 0 name: 'maxLengthEnforcement' style: optional_named argumentValue: expression: 'MaxLengthEnforcement.none' requiredIf: "maxLengthEnforced == 'false'" - kind: 'removeParameter' name: 'maxLengthEnforced' variables: maxLengthEnforced: kind: 'fragment' value: 'arguments[maxLengthEnforced]' # Changes made in https://github.com/flutter/flutter/pull/72043 - title: "Migrate to 'maxLengthEnforcement'" date: 2020-12-13 element: uris: [ 'material.dart' ] field: 'maxLengthEnforced' inClass: 'TextField' changes: - kind: 'rename' newName: 'maxLengthEnforcement' # Changes made in https://github.com/flutter/flutter/pull/72043 - title: "Migrate to 'maxLengthEnforcement'" date: 2020-12-13 element: uris: [ 'material.dart' ] constructor: '' inClass: 'TextField' oneOf: - if: "maxLengthEnforced == 'true'" changes: - kind: 'addParameter' index: 0 name: 'maxLengthEnforcement' style: optional_named argumentValue: expression: 'MaxLengthEnforcement.enforce' requiredIf: "maxLengthEnforced == 'true'" - kind: 'removeParameter' name: 'maxLengthEnforced' - if: "maxLengthEnforced == 'false'" changes: - kind: 'addParameter' index: 0 name: 'maxLengthEnforcement' style: optional_named argumentValue: expression: 'MaxLengthEnforcement.none' requiredIf: "maxLengthEnforced == 'false'" - kind: 'removeParameter' name: 'maxLengthEnforced' variables: maxLengthEnforced: kind: 'fragment' value: 'arguments[maxLengthEnforced]' # Changes made in https://github.com/flutter/flutter/pull/65246 - title: "Remove 'disabledThumbGapWidth'" date: 2020-11-17 element: uris: [ 'material.dart' ] constructor: '' inClass: 'RectangularSliderTrackShape' changes: - kind: 'removeParameter' name: 'disabledThumbGapWidth' # Changes made in https://github.com/flutter/flutter/pull/46115 - title: "Migrate to 'floatingLabelBehavior'" date: 2020-01-15 element: uris: [ 'material.dart' ] field: 'hasFloatingPlaceholder' inClass: 'InputDecorationTheme' changes: - kind: 'rename' newName: 'floatingLabelBehavior' # Changes made in https://github.com/flutter/flutter/pull/46115 - title: "Migrate to 'floatingLabelBehavior'" date: 2020-01-15 element: uris: [ 'material.dart' ] constructor: '' inClass: 'InputDecorationTheme' oneOf: - if: "hasFloatingPlaceholder == 'true'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.auto' requiredIf: "hasFloatingPlaceholder == 'true'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' - if: "hasFloatingPlaceholder == 'false'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.never' requiredIf: "hasFloatingPlaceholder == 'false'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' variables: hasFloatingPlaceholder: kind: 'fragment' value: 'arguments[hasFloatingPlaceholder]' # Changes made in https://github.com/flutter/flutter/pull/46115 - title: "Migrate to 'floatingLabelBehavior'" date: 2020-01-15 element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'InputDecorationTheme' oneOf: - if: "hasFloatingPlaceholder == 'true'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.auto' requiredIf: "hasFloatingPlaceholder == 'true'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' - if: "hasFloatingPlaceholder == 'false'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.never' requiredIf: "hasFloatingPlaceholder == 'false'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' variables: hasFloatingPlaceholder: kind: 'fragment' value: 'arguments[hasFloatingPlaceholder]' # Changes made in https://github.com/flutter/flutter/pull/46115 - title: "Migrate to 'floatingLabelBehavior'" date: 2020-01-15 element: uris: [ 'material.dart' ] field: 'hasFloatingPlaceholder' inClass: 'InputDecoration' changes: - kind: 'rename' newName: 'floatingLabelBehavior' # Changes made in https://github.com/flutter/flutter/pull/46115 - title: "Rename to 'floatingLabelBehavior'" date: 2020-01-15 element: uris: [ 'material.dart' ] constructor: 'collapsed' inClass: 'InputDecoration' oneOf: - if: "hasFloatingPlaceholder == 'true'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.auto' requiredIf: "hasFloatingPlaceholder == 'true'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' - if: "hasFloatingPlaceholder == 'false'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.never' requiredIf: "hasFloatingPlaceholder == 'false'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' variables: hasFloatingPlaceholder: kind: 'fragment' value: 'arguments[hasFloatingPlaceholder]' # Changes made in https://github.com/flutter/flutter/pull/46115 - title: "Rename to 'floatingLabelBehavior'" date: 2020-01-15 element: uris: [ 'material.dart' ] constructor: '' inClass: 'InputDecoration' oneOf: - if: "hasFloatingPlaceholder == 'true'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.auto' requiredIf: "hasFloatingPlaceholder == 'true'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' - if: "hasFloatingPlaceholder == 'false'" changes: - kind: 'addParameter' index: 14 name: 'floatingLabelBehavior' style: optional_named argumentValue: expression: '{% FloatingLabelBehavior %}.never' requiredIf: "hasFloatingPlaceholder == 'false'" variables: FloatingLabelBehavior: kind: 'import' uris: [ 'material.dart' ] name: 'FloatingLabelBehavior' - kind: 'removeParameter' name: 'hasFloatingPlaceholder' variables: hasFloatingPlaceholder: kind: 'fragment' value: 'arguments[hasFloatingPlaceholder]' # Changes made in https://github.com/flutter/flutter/pull/96115 - title: "Migrate 'Icons.pie_chart_outlined' to 'Icons.pie_chart_outline'" date: 2022-01-04 element: uris: [ 'material.dart' ] field: 'pie_chart_outlined' inClass: 'Icons' changes: - kind: 'rename' newName: 'pie_chart_outline' # Changes made in https://github.com/flutter/flutter/pull/96957 - title: "Migrate to 'thumbVisibility'" date: 2022-01-20 element: uris: [ 'material.dart' ] field: 'isAlwaysShown' inClass: 'Scrollbar' changes: - kind: 'rename' newName: 'thumbVisibility' # Changes made in https://github.com/flutter/flutter/pull/96957 - title: "Migrate to 'thumbVisibility'" date: 2022-01-20 element: uris: [ 'material.dart' ] constructor: '' inClass: 'Scrollbar' changes: - kind: 'renameParameter' oldName: 'isAlwaysShown' newName: 'thumbVisibility' # Changes made in https://github.com/flutter/flutter/pull/96957 - title: "Migrate to 'thumbVisibility'" date: 2022-01-20 element: uris: [ 'material.dart' ] field: 'isAlwaysShown' inClass: 'ScrollbarThemeData' changes: - kind: 'rename' newName: 'thumbVisibility' # Changes made in https://github.com/flutter/flutter/pull/96957 - title: "Migrate to 'thumbVisibility'" date: 2022-01-20 element: uris: [ 'material.dart' ] constructor: '' inClass: 'ScrollbarThemeData' changes: - kind: 'renameParameter' oldName: 'isAlwaysShown' newName: 'thumbVisibility' # Changes made in https://github.com/flutter/flutter/pull/96957 - title: "Migrate to 'thumbVisibility'" date: 2022-01-20 element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'ScrollbarThemeData' changes: - kind: 'renameParameter' oldName: 'isAlwaysShown' newName: 'thumbVisibility' # Changes made in https://github.com/flutter/flutter/pull/96174 - title: "Migrate 'useDeleteButtonTooltip' to 'deleteButtonTooltipMessage'" date: 2022-01-05 element: uris: [ 'material.dart' ] constructor: '' inClass: 'Chip' changes: - kind: 'addParameter' index: 9 name: 'deleteButtonTooltipMessage' style: optional_named argumentValue: expression: "''" requiredIf: "useDeleteButtonTooltip == 'false' && deleteButtonTooltipMessage == ''" - kind: 'removeParameter' name: 'useDeleteButtonTooltip' variables: useDeleteButtonTooltip: kind: 'fragment' value: 'arguments[useDeleteButtonTooltip]' deleteButtonTooltipMessage: kind: 'fragment' value: 'arguments[deleteButtonTooltipMessage]' # Changes made in https://github.com/flutter/flutter/pull/96174 - title: "Migrate 'useDeleteButtonTooltip' to 'deleteButtonTooltipMessage'" date: 2022-01-05 element: uris: [ 'material.dart' ] constructor: '' inClass: 'InputChip' changes: - kind: 'addParameter' index: 9 name: 'deleteButtonTooltipMessage' style: optional_named argumentValue: expression: "''" requiredIf: "useDeleteButtonTooltip == 'false' && deleteButtonTooltipMessage == ''" - kind: 'removeParameter' name: 'useDeleteButtonTooltip' variables: useDeleteButtonTooltip: kind: 'fragment' value: 'arguments[useDeleteButtonTooltip]' deleteButtonTooltipMessage: kind: 'fragment' value: 'arguments[deleteButtonTooltipMessage]' # Changes made in https://github.com/flutter/flutter/pull/96174 - title: "Migrate 'useDeleteButtonTooltip' to 'deleteButtonTooltipMessage'" date: 2022-01-05 element: uris: [ 'material.dart' ] constructor: '' inClass: 'RawChip' changes: - kind: 'addParameter' index: 9 name: 'deleteButtonTooltipMessage' style: optional_named argumentValue: expression: "''" requiredIf: "useDeleteButtonTooltip == 'false' && deleteButtonTooltipMessage == ''" - kind: 'removeParameter' name: 'useDeleteButtonTooltip' variables: useDeleteButtonTooltip: kind: 'fragment' value: 'arguments[useDeleteButtonTooltip]' deleteButtonTooltipMessage: kind: 'fragment' value: 'arguments[deleteButtonTooltipMessage]' # Changes made in https://github.com/flutter/flutter/pull/96174 - title: "Migrate 'useDeleteButtonTooltip' to 'deleteButtonTooltipMessage'" date: 2022-01-05 element: uris: [ 'material.dart' ] field: 'useDeleteButtonTooltip' inClass: 'Chip' changes: - kind: 'rename' newName: 'deleteButtonTooltipMessage' # Changes made in https://github.com/flutter/flutter/pull/96174 - title: "Migrate 'useDeleteButtonTooltip' to 'deleteButtonTooltipMessage'" date: 2022-01-05 element: uris: [ 'material.dart' ] field: 'useDeleteButtonTooltip' inClass: 'InputChip' changes: - kind: 'rename' newName: 'deleteButtonTooltipMessage' # Changes made in https://github.com/flutter/flutter/pull/96174 - title: "Migrate 'useDeleteButtonTooltip' to 'deleteButtonTooltipMessage'" date: 2022-01-05 element: uris: [ 'material.dart' ] field: 'useDeleteButtonTooltip' inClass: 'RawChip' changes: - kind: 'rename' newName: 'deleteButtonTooltipMessage' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'ElevatedButton.styleFrom(primary)' to 'ElevatedButton.styleFrom(backgroundColor)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'ElevatedButton' changes: - kind: 'addParameter' index: 1 name: 'backgroundColor' style: optional_named argumentValue: expression: '{% primary %}' requiredIf: "primary != ''" - kind: 'removeParameter' name: 'primary' variables: primary: kind: 'fragment' value: 'arguments[primary]' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'ElevatedButton.styleFrom(onPrimary)' to 'ElevatedButton.styleFrom(foregroundColor)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'ElevatedButton' changes: - kind: 'addParameter' index: 0 name: 'foregroundColor' style: optional_named argumentValue: expression: '{% onPrimary %}' requiredIf: "onPrimary != ''" - kind: 'removeParameter' name: 'onPrimary' variables: onPrimary: kind: 'fragment' value: 'arguments[onPrimary]' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'ElevatedButton.styleFrom(onSurface)' to 'ElevatedButton.styleFrom(disabledForegroundColor)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'ElevatedButton' changes: - kind: 'addParameter' index: 2 name: 'disabledForegroundColor' style: optional_named argumentValue: expression: '{% onSurface %}.withOpacity(0.38)' requiredIf: "onSurface != ''" - kind: 'addParameter' index: 3 name: 'disabledBackgroundColor' style: optional_named argumentValue: expression: '{% onSurface %}.withOpacity(0.12)' requiredIf: "onSurface != ''" - kind: 'removeParameter' name: 'onSurface' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'OutlinedButton.styleFrom(primary)' to 'OutlinedButton.styleFrom(foregroundColor)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'OutlinedButton' changes: - kind: 'addParameter' index: 0 name: 'foregroundColor' style: optional_named argumentValue: expression: '{% primary %}' requiredIf: "primary != ''" - kind: 'removeParameter' name: 'primary' variables: primary: kind: 'fragment' value: 'arguments[primary]' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'OutlinedButton.styleFrom(onSurface)' to 'OutlinedButton.styleFrom(disabledForeground)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'OutlinedButton' changes: - kind: 'addParameter' index: 2 name: 'disabledForegroundColor' style: optional_named argumentValue: expression: '{% onSurface %}.withOpacity(0.38)' requiredIf: "onSurface != ''" - kind: 'removeParameter' name: 'onSurface' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'TextButton.styleFrom(primary)' to 'TextButton.styleFrom(foregroundColor)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'TextButton' changes: - kind: 'addParameter' index: 0 name: 'foregroundColor' style: optional_named argumentValue: expression: '{% primary %}' requiredIf: "primary != ''" - kind: 'removeParameter' name: 'primary' variables: primary: kind: 'fragment' value: 'arguments[primary]' # Changes made in https://github.com/flutter/flutter/pull/105291 - title: "Migrate 'TextButton.styleFrom(onSurface)' to 'TextButton.styleFrom(disabledForeground)'" date: 2022-05-27 element: uris: [ 'material.dart' ] method: 'styleFrom' inClass: 'TextButton' changes: - kind: 'addParameter' index: 2 name: 'disabledForegroundColor' style: optional_named argumentValue: expression: '{% onSurface %}.withOpacity(0.38)' requiredIf: "onSurface != ''" - kind: 'removeParameter' name: 'onSurface' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/78588 - title: "Migrate to 'buildOverscrollIndicator'" date: 2021-03-18 element: uris: [ 'material.dart' ] method: 'buildViewportChrome' inClass: 'MaterialScrollBehavior' changes: - kind: 'rename' newName: 'buildOverscrollIndicator' # Changes made in https://github.com/flutter/flutter/pull/111706 - title: "Migrate to 'trackVisibility'" date: 2022-09-15 element: uris: [ 'material.dart' ] field: 'showTrackOnHover' inClass: 'Scrollbar' changes: - kind: 'rename' newName: 'trackVisibility' # Changes made in https://github.com/flutter/flutter/pull/111706 - title: "Migrate to 'trackVisibility'" date: 2022-09-15 element: uris: [ 'material.dart' ] constructor: '' inClass: 'Scrollbar' changes: - kind: 'renameParameter' oldName: 'showTrackOnHover' newName: 'trackVisibility' # Changes made in https://github.com/flutter/flutter/pull/111706 - title: "Migrate to 'trackVisibility'" date: 2022-09-15 bulkApply: false element: uris: [ 'material.dart' ] field: 'showTrackOnHover' inClass: 'ScrollbarThemeData' changes: - kind: 'rename' newName: 'trackVisibility' # Changes made in https://github.com/flutter/flutter/pull/111706 - title: "Migrate to 'thumbVisibility'" date: 2022-09-15 bulkApply: false element: uris: [ 'material.dart' ] constructor: '' inClass: 'ScrollbarThemeData' changes: - kind: 'renameParameter' oldName: 'showTrackOnHover' newName: 'trackVisibility' # Changes made in https://github.com/flutter/flutter/pull/111706 - title: "Migrate to 'trackVisibility'" date: 2022-09-15 bulkApply: false element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'ScrollbarThemeData' changes: - kind: 'renameParameter' oldName: 'showTrackOnHover' newName: 'trackVisibility' # Changes made in https://github.com/flutter/flutter/pull/134417 - title: "Migrate to 'Easing.legacy'" date: 2023-12-12 element: uris: [ 'material.dart' ] variable: 'standardEasing' changes: - kind: 'replacedBy' newElement: uris: [ 'material.dart' ] field: legacy inClass: Easing # Changes made in https://github.com/flutter/flutter/pull/134417 - title: "Migrate to 'Easing.legacyAccelerate'" date: 2023-12-12 element: uris: [ 'material.dart' ] variable: 'accelerateEasing' changes: - kind: 'replacedBy' newElement: uris: [ 'material.dart' ] field: legacyAccelerate inClass: Easing # Changes made in https://github.com/flutter/flutter/pull/134417 - title: "Migrate to 'Easing.legacyDecelerate'" date: 2023-12-12 element: uris: [ 'material.dart' ] variable: 'decelerateEasing' changes: - kind: 'replacedBy' newElement: uris: [ 'material.dart' ] field: legacyDecelerate inClass: Easing # Before adding a new fix: read instructions at the top of this file.
flutter/packages/flutter/lib/fix_data/fix_material/fix_material.yaml/0
{ "file_path": "flutter/packages/flutter/lib/fix_data/fix_material/fix_material.yaml", "repo_id": "flutter", "token_count": 13536 }
664
// 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 'animation.dart'; export 'dart:ui' show VoidCallback; export 'animation.dart' show AnimationStatus, AnimationStatusListener; /// A mixin that helps listen to another object only when this object has registered listeners. /// /// This mixin provides implementations of [didRegisterListener] and [didUnregisterListener], /// and therefore can be used in conjunction with mixins that require these methods, /// [AnimationLocalListenersMixin] and [AnimationLocalStatusListenersMixin]. mixin AnimationLazyListenerMixin { int _listenerCounter = 0; /// Calls [didStartListening] every time a registration of a listener causes /// an empty list of listeners to become non-empty. /// /// See also: /// /// * [didUnregisterListener], which may cause the listener list to /// become empty again, and in turn cause this method to call /// [didStartListening] again. @protected void didRegisterListener() { assert(_listenerCounter >= 0); if (_listenerCounter == 0) { didStartListening(); } _listenerCounter += 1; } /// Calls [didStopListening] when an only remaining listener is unregistered, /// thus making the list empty. /// /// See also: /// /// * [didRegisterListener], which causes the listener list to become non-empty. @protected void didUnregisterListener() { assert(_listenerCounter >= 1); _listenerCounter -= 1; if (_listenerCounter == 0) { didStopListening(); } } /// Called when the number of listeners changes from zero to one. @protected void didStartListening(); /// Called when the number of listeners changes from one to zero. @protected void didStopListening(); /// Whether there are any listeners. bool get isListening => _listenerCounter > 0; } /// A mixin that replaces the [didRegisterListener]/[didUnregisterListener] contract /// with a dispose contract. /// /// This mixin provides implementations of [didRegisterListener] and [didUnregisterListener], /// and therefore can be used in conjunction with mixins that require these methods, /// [AnimationLocalListenersMixin] and [AnimationLocalStatusListenersMixin]. mixin AnimationEagerListenerMixin { /// This implementation ignores listener registrations. @protected void didRegisterListener() { } /// This implementation ignores listener registrations. @protected void didUnregisterListener() { } /// Release the resources used by this object. The object is no longer usable /// after this method is called. @mustCallSuper void dispose() { } } /// A mixin that implements the [addListener]/[removeListener] protocol and notifies /// all the registered listeners when [notifyListeners] is called. /// /// This mixin requires that the mixing class provide methods [didRegisterListener] /// and [didUnregisterListener]. Implementations of these methods can be obtained /// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin]. mixin AnimationLocalListenersMixin { final ObserverList<VoidCallback> _listeners = ObserverList<VoidCallback>(); /// Called immediately before a listener is added via [addListener]. /// /// At the time this method is called the registered listener is not yet /// notified by [notifyListeners]. @protected void didRegisterListener(); /// Called immediately after a listener is removed via [removeListener]. /// /// At the time this method is called the removed listener is no longer /// notified by [notifyListeners]. @protected void didUnregisterListener(); /// Calls the listener every time the value of the animation changes. /// /// Listeners can be removed with [removeListener]. void addListener(VoidCallback listener) { didRegisterListener(); _listeners.add(listener); } /// Stop calling the listener every time the value of the animation changes. /// /// Listeners can be added with [addListener]. void removeListener(VoidCallback listener) { final bool removed = _listeners.remove(listener); if (removed) { didUnregisterListener(); } } /// Removes all listeners added with [addListener]. /// /// This method is typically called from the `dispose` method of the class /// using this mixin if the class also uses the [AnimationEagerListenerMixin]. /// /// Calling this method will not trigger [didUnregisterListener]. @protected void clearListeners() { _listeners.clear(); } /// Calls all the listeners. /// /// If listeners are added or removed during this function, the modifications /// will not change which listeners are called during this iteration. @protected @pragma('vm:notify-debugger-on-exception') void notifyListeners() { final List<VoidCallback> localListeners = _listeners.toList(growable: false); for (final VoidCallback listener in localListeners) { InformationCollector? collector; assert(() { collector = () => <DiagnosticsNode>[ DiagnosticsProperty<AnimationLocalListenersMixin>( 'The $runtimeType notifying listeners was', this, style: DiagnosticsTreeStyle.errorProperty, ), ]; return true; }()); try { if (_listeners.contains(listener)) { listener(); } } catch (exception, stack) { FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'animation library', context: ErrorDescription('while notifying listeners for $runtimeType'), informationCollector: collector, )); } } } } /// A mixin that implements the addStatusListener/removeStatusListener protocol /// and notifies all the registered listeners when notifyStatusListeners is /// called. /// /// This mixin requires that the mixing class provide methods [didRegisterListener] /// and [didUnregisterListener]. Implementations of these methods can be obtained /// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin]. mixin AnimationLocalStatusListenersMixin { final ObserverList<AnimationStatusListener> _statusListeners = ObserverList<AnimationStatusListener>(); /// Called immediately before a status listener is added via [addStatusListener]. /// /// At the time this method is called the registered listener is not yet /// notified by [notifyStatusListeners]. @protected void didRegisterListener(); /// Called immediately after a status listener is removed via [removeStatusListener]. /// /// At the time this method is called the removed listener is no longer /// notified by [notifyStatusListeners]. @protected void didUnregisterListener(); /// Calls listener every time the status of the animation changes. /// /// Listeners can be removed with [removeStatusListener]. void addStatusListener(AnimationStatusListener listener) { didRegisterListener(); _statusListeners.add(listener); } /// Stops calling the listener every time the status of the animation changes. /// /// Listeners can be added with [addStatusListener]. void removeStatusListener(AnimationStatusListener listener) { final bool removed = _statusListeners.remove(listener); if (removed) { didUnregisterListener(); } } /// Removes all listeners added with [addStatusListener]. /// /// This method is typically called from the `dispose` method of the class /// using this mixin if the class also uses the [AnimationEagerListenerMixin]. /// /// Calling this method will not trigger [didUnregisterListener]. @protected void clearStatusListeners() { _statusListeners.clear(); } /// Calls all the status listeners. /// /// If listeners are added or removed during this function, the modifications /// will not change which listeners are called during this iteration. @protected @pragma('vm:notify-debugger-on-exception') void notifyStatusListeners(AnimationStatus status) { final List<AnimationStatusListener> localListeners = _statusListeners.toList(growable: false); for (final AnimationStatusListener listener in localListeners) { try { if (_statusListeners.contains(listener)) { listener(status); } } catch (exception, stack) { InformationCollector? collector; assert(() { collector = () => <DiagnosticsNode>[ DiagnosticsProperty<AnimationLocalStatusListenersMixin>( 'The $runtimeType notifying status listeners was', this, style: DiagnosticsTreeStyle.errorProperty, ), ]; return true; }()); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'animation library', context: ErrorDescription('while notifying status listeners for $runtimeType'), informationCollector: collector, )); } } } }
flutter/packages/flutter/lib/src/animation/listener_helpers.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/animation/listener_helpers.dart", "repo_id": "flutter", "token_count": 2728 }
665
// 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'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; // The minimum padding from all edges of the selection toolbar to all edges of // the screen. const double _kToolbarScreenPadding = 8.0; // These values were measured from a screenshot of the native context menu on // macOS 13.2 on a Macbook Pro. const double _kToolbarSaturationBoost = 3; const double _kToolbarBlurSigma = 20; const double _kToolbarWidth = 222.0; const Radius _kToolbarBorderRadius = Radius.circular(8.0); const EdgeInsets _kToolbarPadding = EdgeInsets.all(6.0); const List<BoxShadow> _kToolbarShadow = <BoxShadow>[ BoxShadow( color: Color.fromARGB(60, 0, 0, 0), blurRadius: 10.0, spreadRadius: 0.5, offset: Offset(0.0, 4.0), ), ]; // These values were measured from a screenshot of the native context menu on // macOS 13.2 on a Macbook Pro. const CupertinoDynamicColor _kToolbarBorderColor = CupertinoDynamicColor.withBrightness( color: Color(0xFFB8B8B8), darkColor: Color(0xFF5B5B5B), ); const CupertinoDynamicColor _kToolbarBackgroundColor = CupertinoDynamicColor.withBrightness( color: Color(0xB2FFFFFF), darkColor: Color(0xB2303030), ); /// A macOS-style text selection toolbar. /// /// Typically displays buttons for text manipulation, e.g. copying and pasting /// text. /// /// Tries to position itself as closely as possible to [anchor] while remaining /// fully inside the viewport. /// /// See also: /// /// * [CupertinoAdaptiveTextSelectionToolbar], where this is used to build the /// toolbar for desktop platforms. /// * [AdaptiveTextSelectionToolbar], where this is used to build the toolbar on /// macOS. /// * [DesktopTextSelectionToolbar], which is similar but builds a /// Material-style desktop toolbar. class CupertinoDesktopTextSelectionToolbar extends StatelessWidget { /// Creates a const instance of CupertinoTextSelectionToolbar. const CupertinoDesktopTextSelectionToolbar({ super.key, required this.anchor, required this.children, }) : assert(children.length > 0); /// Creates a 5x5 matrix that increases saturation when used with [ColorFilter.matrix]. /// /// The numbers were taken from this comment: /// [Cupertino blurs should boost saturation](https://github.com/flutter/flutter/issues/29483#issuecomment-477334981). static List<double> _matrixWithSaturation(double saturation) { final double r = 0.213 * (1 - saturation); final double g = 0.715 * (1 - saturation); final double b = 0.072 * (1 - saturation); return <double>[ r + saturation, g, b, 0, 0, // r, g + saturation, b, 0, 0, // r, g, b + saturation, 0, 0, // 0, 0, 0, 1, 0, // ]; } /// {@macro flutter.material.DesktopTextSelectionToolbar.anchor} final Offset anchor; /// {@macro flutter.material.TextSelectionToolbar.children} /// /// See also: /// * [CupertinoDesktopTextSelectionToolbarButton], which builds a default /// macOS-style text selection toolbar text button. final List<Widget> children; // Builds a toolbar just like the default Mac toolbar, with the right color // background, padding, and rounded corners. static Widget _defaultToolbarBuilder(BuildContext context, Widget child) { return Container( width: _kToolbarWidth, clipBehavior: Clip.hardEdge, decoration: const BoxDecoration( boxShadow: _kToolbarShadow, borderRadius: BorderRadius.all(_kToolbarBorderRadius), ), child: BackdropFilter( // Flutter web doesn't support ImageFilter.compose on CanvasKit yet // (https://github.com/flutter/flutter/issues/120123). filter: kIsWeb ? ImageFilter.blur( sigmaX: _kToolbarBlurSigma, sigmaY: _kToolbarBlurSigma, ) : ImageFilter.compose( outer: ColorFilter.matrix( _matrixWithSaturation(_kToolbarSaturationBoost), ), inner: ImageFilter.blur( sigmaX: _kToolbarBlurSigma, sigmaY: _kToolbarBlurSigma, ), ), child: DecoratedBox( decoration: BoxDecoration( color: _kToolbarBackgroundColor.resolveFrom(context), border: Border.all( color: _kToolbarBorderColor.resolveFrom(context), ), borderRadius: const BorderRadius.all(_kToolbarBorderRadius), ), child: Padding( padding: _kToolbarPadding, child: child, ), ), ), ); } @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding; final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove); return Padding( padding: EdgeInsets.fromLTRB( _kToolbarScreenPadding, paddingAbove, _kToolbarScreenPadding, _kToolbarScreenPadding, ), child: CustomSingleChildLayout( delegate: DesktopTextSelectionToolbarLayoutDelegate( anchor: anchor - localAdjustment, ), child: _defaultToolbarBuilder( context, Column( mainAxisSize: MainAxisSize.min, children: children, ), ), ), ); } }
flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart", "repo_id": "flutter", "token_count": 2190 }
666
// 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/foundation.dart' show clampDouble; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'activity_indicator.dart'; const double _kActivityIndicatorRadius = 14.0; const double _kActivityIndicatorMargin = 16.0; class _CupertinoSliverRefresh extends SingleChildRenderObjectWidget { const _CupertinoSliverRefresh({ this.refreshIndicatorLayoutExtent = 0.0, this.hasLayoutExtent = false, super.child, }) : assert(refreshIndicatorLayoutExtent >= 0.0); // The amount of space the indicator should occupy in the sliver in a // resting state when in the refreshing mode. final double refreshIndicatorLayoutExtent; // _RenderCupertinoSliverRefresh will paint the child in the available // space either way but this instructs the _RenderCupertinoSliverRefresh // on whether to also occupy any layoutExtent space or not. final bool hasLayoutExtent; @override _RenderCupertinoSliverRefresh createRenderObject(BuildContext context) { return _RenderCupertinoSliverRefresh( refreshIndicatorExtent: refreshIndicatorLayoutExtent, hasLayoutExtent: hasLayoutExtent, ); } @override void updateRenderObject(BuildContext context, covariant _RenderCupertinoSliverRefresh renderObject) { renderObject ..refreshIndicatorLayoutExtent = refreshIndicatorLayoutExtent ..hasLayoutExtent = hasLayoutExtent; } } // RenderSliver object that gives its child RenderBox object space to paint // in the overscrolled gap and may or may not hold that overscrolled gap // around the RenderBox depending on whether [layoutExtent] is set. // // The [layoutExtentOffsetCompensation] field keeps internal accounting to // prevent scroll position jumps as the [layoutExtent] is set and unset. class _RenderCupertinoSliverRefresh extends RenderSliver with RenderObjectWithChildMixin<RenderBox> { _RenderCupertinoSliverRefresh({ required double refreshIndicatorExtent, required bool hasLayoutExtent, RenderBox? child, }) : assert(refreshIndicatorExtent >= 0.0), _refreshIndicatorExtent = refreshIndicatorExtent, _hasLayoutExtent = hasLayoutExtent { this.child = child; } // The amount of layout space the indicator should occupy in the sliver in a // resting state when in the refreshing mode. double get refreshIndicatorLayoutExtent => _refreshIndicatorExtent; double _refreshIndicatorExtent; set refreshIndicatorLayoutExtent(double value) { assert(value >= 0.0); if (value == _refreshIndicatorExtent) { return; } _refreshIndicatorExtent = value; markNeedsLayout(); } // The child box will be laid out and painted in the available space either // way but this determines whether to also occupy any // [SliverGeometry.layoutExtent] space or not. bool get hasLayoutExtent => _hasLayoutExtent; bool _hasLayoutExtent; set hasLayoutExtent(bool value) { if (value == _hasLayoutExtent) { return; } _hasLayoutExtent = value; markNeedsLayout(); } // This keeps track of the previously applied scroll offsets to the scrollable // so that when [refreshIndicatorLayoutExtent] or [hasLayoutExtent] changes, // the appropriate delta can be applied to keep everything in the same place // visually. double layoutExtentOffsetCompensation = 0.0; @override void performLayout() { final SliverConstraints constraints = this.constraints; // Only pulling to refresh from the top is currently supported. assert(constraints.axisDirection == AxisDirection.down); assert(constraints.growthDirection == GrowthDirection.forward); // The new layout extent this sliver should now have. final double layoutExtent = (_hasLayoutExtent ? 1.0 : 0.0) * _refreshIndicatorExtent; // If the new layoutExtent instructive changed, the SliverGeometry's // layoutExtent will take that value (on the next performLayout run). Shift // the scroll offset first so it doesn't make the scroll position suddenly jump. if (layoutExtent != layoutExtentOffsetCompensation) { geometry = SliverGeometry( scrollOffsetCorrection: layoutExtent - layoutExtentOffsetCompensation, ); layoutExtentOffsetCompensation = layoutExtent; // Return so we don't have to do temporary accounting and adjusting the // child's constraints accounting for this one transient frame using a // combination of existing layout extent, new layout extent change and // the overlap. return; } final bool active = constraints.overlap < 0.0 || layoutExtent > 0.0; final double overscrolledExtent = constraints.overlap < 0.0 ? constraints.overlap.abs() : 0.0; // Layout the child giving it the space of the currently dragged overscroll // which may or may not include a sliver layout extent space that it will // keep after the user lets go during the refresh process. child!.layout( constraints.asBoxConstraints( maxExtent: layoutExtent // Plus only the overscrolled portion immediately preceding this // sliver. + overscrolledExtent, ), parentUsesSize: true, ); if (active) { geometry = SliverGeometry( scrollExtent: layoutExtent, paintOrigin: -overscrolledExtent - constraints.scrollOffset, paintExtent: max( // Check child size (which can come from overscroll) because // layoutExtent may be zero. Check layoutExtent also since even // with a layoutExtent, the indicator builder may decide to not // build anything. max(child!.size.height, layoutExtent) - constraints.scrollOffset, 0.0, ), maxPaintExtent: max( max(child!.size.height, layoutExtent) - constraints.scrollOffset, 0.0, ), layoutExtent: max(layoutExtent - constraints.scrollOffset, 0.0), ); } else { // If we never started overscrolling, return no geometry. geometry = SliverGeometry.zero; } } @override void paint(PaintingContext paintContext, Offset offset) { if (constraints.overlap < 0.0 || constraints.scrollOffset + child!.size.height > 0) { paintContext.paintChild(child!, offset); } } // Nothing special done here because this sliver always paints its child // exactly between paintOrigin and paintExtent. @override void applyPaintTransform(RenderObject child, Matrix4 transform) { } } /// The current state of the refresh control. /// /// Passed into the [RefreshControlIndicatorBuilder] builder function so /// users can show different UI in different modes. enum RefreshIndicatorMode { /// Initial state, when not being overscrolled into, or after the overscroll /// is canceled or after done and the sliver retracted away. inactive, /// While being overscrolled but not far enough yet to trigger the refresh. drag, /// Dragged far enough that the onRefresh callback will run and the dragged /// displacement is not yet at the final refresh resting state. armed, /// While the onRefresh task is running. refresh, /// While the indicator is animating away after refreshing. done, } /// Signature for a builder that can create a different widget to show in the /// refresh indicator space depending on the current state of the refresh /// control and the space available. /// /// The `refreshTriggerPullDistance` and `refreshIndicatorExtent` parameters are /// the same values passed into the [CupertinoSliverRefreshControl]. /// /// The `pulledExtent` parameter is the currently available space either from /// overscrolling or as held by the sliver during refresh. typedef RefreshControlIndicatorBuilder = Widget Function( BuildContext context, RefreshIndicatorMode refreshState, double pulledExtent, double refreshTriggerPullDistance, double refreshIndicatorExtent, ); /// A callback function that's invoked when the [CupertinoSliverRefreshControl] is /// pulled a `refreshTriggerPullDistance`. Must return a [Future]. Upon /// completion of the [Future], the [CupertinoSliverRefreshControl] enters the /// [RefreshIndicatorMode.done] state and will start to go away. typedef RefreshCallback = Future<void> Function(); /// A sliver widget implementing the iOS-style pull to refresh content control. /// /// When inserted as the first sliver in a scroll view or behind other slivers /// that still lets the scrollable overscroll in front of this sliver (such as /// the [CupertinoSliverNavigationBar], this widget will: /// /// * Let the user draw inside the overscrolled area via the passed in [builder]. /// * Trigger the provided [onRefresh] function when overscrolled far enough to /// pass [refreshTriggerPullDistance]. /// * Continue to hold [refreshIndicatorExtent] amount of space for the [builder] /// to keep drawing inside of as the [Future] returned by [onRefresh] processes. /// * Scroll away once the [onRefresh] [Future] completes. /// /// The [builder] function will be informed of the current [RefreshIndicatorMode] /// when invoking it, except in the [RefreshIndicatorMode.inactive] state when /// no space is available and nothing needs to be built. The [builder] function /// will otherwise be continuously invoked as the amount of space available /// changes from overscroll, as the sliver scrolls away after the [onRefresh] /// task is done, etc. /// /// Only one refresh can be triggered until the previous refresh has completed /// and the indicator sliver has retracted at least 90% of the way back. /// /// Can only be used in downward-scrolling vertical lists that overscrolls. In /// other words, refreshes can't be triggered with [Scrollable]s using /// [ClampingScrollPhysics] which is the default on Android. To allow overscroll /// on Android, use an overscrolling physics such as [BouncingScrollPhysics]. /// This can be done via: /// /// * Providing a [BouncingScrollPhysics] (possibly in combination with a /// [AlwaysScrollableScrollPhysics]) while constructing the scrollable. /// * By inserting a [ScrollConfiguration] with [BouncingScrollPhysics] above /// the scrollable. /// * By using [CupertinoApp], which always uses a [ScrollConfiguration] /// with [BouncingScrollPhysics] regardless of platform. /// /// In a typical application, this sliver should be inserted between the app bar /// sliver such as [CupertinoSliverNavigationBar] and your main scrollable /// content's sliver. /// /// {@tool dartpad} /// When the user scrolls past [refreshTriggerPullDistance], /// this sample shows the default iOS pull to refresh indicator for 1 second and /// adds a new item to the top of the list view. /// /// ** See code in examples/api/lib/cupertino/refresh/cupertino_sliver_refresh_control.0.dart ** /// {@end-tool} /// /// See also: /// /// * [CustomScrollView], a typical sliver holding scroll view this control /// should go into. /// * <https://developer.apple.com/ios/human-interface-guidelines/controls/refresh-content-controls/> /// * [RefreshIndicator], a Material Design version of the pull-to-refresh /// paradigm. This widget works differently than [RefreshIndicator] because /// instead of being an overlay on top of the scrollable, the /// [CupertinoSliverRefreshControl] is part of the scrollable and actively occupies /// scrollable space. class CupertinoSliverRefreshControl extends StatefulWidget { /// Create a new refresh control for inserting into a list of slivers. /// /// The [refreshTriggerPullDistance] and [refreshIndicatorExtent] arguments /// must be greater than or equal to 0. /// /// The [builder] argument may be null, in which case no indicator UI will be /// shown but the [onRefresh] will still be invoked. By default, [builder] /// shows a [CupertinoActivityIndicator]. /// /// The [onRefresh] argument will be called when pulled far enough to trigger /// a refresh. const CupertinoSliverRefreshControl({ super.key, this.refreshTriggerPullDistance = _defaultRefreshTriggerPullDistance, this.refreshIndicatorExtent = _defaultRefreshIndicatorExtent, this.builder = buildRefreshIndicator, this.onRefresh, }) : assert(refreshTriggerPullDistance > 0.0), assert(refreshIndicatorExtent >= 0.0), assert( refreshTriggerPullDistance >= refreshIndicatorExtent, 'The refresh indicator cannot take more space in its final state ' 'than the amount initially created by overscrolling.', ); /// The amount of overscroll the scrollable must be dragged to trigger a reload. /// /// Must be larger than zero and larger than [refreshIndicatorExtent]. /// Defaults to 100 pixels when not specified. /// /// When overscrolled past this distance, [onRefresh] will be called if not /// null and the [builder] will build in the [RefreshIndicatorMode.armed] state. final double refreshTriggerPullDistance; /// The amount of space the refresh indicator sliver will keep holding while /// [onRefresh]'s [Future] is still running. /// /// Must be a positive number, but can be zero, in which case the sliver will /// start retracting back to zero as soon as the refresh is started. Defaults /// to 60 pixels when not specified. /// /// Must be smaller than [refreshTriggerPullDistance], since the sliver /// shouldn't grow further after triggering the refresh. final double refreshIndicatorExtent; /// A builder that's called as this sliver's size changes, and as the state /// changes. /// /// Can be set to null, in which case nothing will be drawn in the overscrolled /// space. /// /// Will not be called when the available space is zero such as before any /// overscroll. final RefreshControlIndicatorBuilder? builder; /// Callback invoked when pulled by [refreshTriggerPullDistance]. /// /// If provided, must return a [Future] which will keep the indicator in the /// [RefreshIndicatorMode.refresh] state until the [Future] completes. /// /// Can be null, in which case a single frame of [RefreshIndicatorMode.armed] /// state will be drawn before going immediately to the [RefreshIndicatorMode.done] /// where the sliver will start retracting. final RefreshCallback? onRefresh; static const double _defaultRefreshTriggerPullDistance = 100.0; static const double _defaultRefreshIndicatorExtent = 60.0; /// Retrieve the current state of the CupertinoSliverRefreshControl. The same as the /// state that gets passed into the [builder] function. Used for testing. @visibleForTesting static RefreshIndicatorMode state(BuildContext context) { final _CupertinoSliverRefreshControlState state = context.findAncestorStateOfType<_CupertinoSliverRefreshControlState>()!; return state.refreshState; } /// Builds a refresh indicator that reflects the standard iOS pull-to-refresh /// behavior. Specifically, this entails presenting an activity indicator that /// changes depending on the current refreshState. As the user initially drags /// down, the indicator will gradually reveal individual ticks until the refresh /// becomes armed. At this point, the animated activity indicator will begin rotating. /// Once the refresh has completed, the activity indicator shrinks away as the /// space allocation animates back to closed. static Widget buildRefreshIndicator( BuildContext context, RefreshIndicatorMode refreshState, double pulledExtent, double refreshTriggerPullDistance, double refreshIndicatorExtent, ) { final double percentageComplete = clampDouble(pulledExtent / refreshTriggerPullDistance, 0.0, 1.0); // Place the indicator at the top of the sliver that opens up. We're using a // Stack/Positioned widget because the CupertinoActivityIndicator does some // internal translations based on the current size (which grows as the user drags) // that makes Padding calculations difficult. Rather than be reliant on the // internal implementation of the activity indicator, the Positioned widget allows // us to be explicit where the widget gets placed. The indicator should appear // over the top of the dragged widget, hence the use of Clip.none. return Center( child: Stack( clipBehavior: Clip.none, children: <Widget>[ Positioned( top: _kActivityIndicatorMargin, left: 0.0, right: 0.0, child: _buildIndicatorForRefreshState(refreshState, _kActivityIndicatorRadius, percentageComplete), ), ], ), ); } static Widget _buildIndicatorForRefreshState(RefreshIndicatorMode refreshState, double radius, double percentageComplete) { switch (refreshState) { case RefreshIndicatorMode.drag: // While we're dragging, we draw individual ticks of the spinner while simultaneously // easing the opacity in. The opacity curve values here were derived using // Xcode through inspecting a native app running on iOS 13.5. const Curve opacityCurve = Interval(0.0, 0.35, curve: Curves.easeInOut); return Opacity( opacity: opacityCurve.transform(percentageComplete), child: CupertinoActivityIndicator.partiallyRevealed(radius: radius, progress: percentageComplete), ); case RefreshIndicatorMode.armed: case RefreshIndicatorMode.refresh: // Once we're armed or performing the refresh, we just show the normal spinner. return CupertinoActivityIndicator(radius: radius); case RefreshIndicatorMode.done: // When the user lets go, the standard transition is to shrink the spinner. return CupertinoActivityIndicator(radius: radius * percentageComplete); case RefreshIndicatorMode.inactive: // Anything else doesn't show anything. return const SizedBox.shrink(); } } @override State<CupertinoSliverRefreshControl> createState() => _CupertinoSliverRefreshControlState(); } class _CupertinoSliverRefreshControlState extends State<CupertinoSliverRefreshControl> { // Reset the state from done to inactive when only this fraction of the // original `refreshTriggerPullDistance` is left. static const double _inactiveResetOverscrollFraction = 0.1; late RefreshIndicatorMode refreshState; // [Future] returned by the widget's `onRefresh`. Future<void>? refreshTask; // The amount of space available from the inner indicator box's perspective. // // The value is the sum of the sliver's layout extent and the overscroll // (which partially gets transferred into the layout extent when the refresh // triggers). // // The value of latestIndicatorBoxExtent doesn't change when the sliver scrolls // away without retracting; it is independent from the sliver's scrollOffset. double latestIndicatorBoxExtent = 0.0; bool hasSliverLayoutExtent = false; @override void initState() { super.initState(); refreshState = RefreshIndicatorMode.inactive; } // A state machine transition calculator. Multiple states can be transitioned // through per single call. RefreshIndicatorMode transitionNextState() { RefreshIndicatorMode nextState; void goToDone() { nextState = RefreshIndicatorMode.done; // Either schedule the RenderSliver to re-layout on the next frame // when not currently in a frame or schedule it on the next frame. if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle) { setState(() => hasSliverLayoutExtent = false); } else { SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) { setState(() => hasSliverLayoutExtent = false); }, debugLabel: 'Refresh.goToDone'); } } switch (refreshState) { case RefreshIndicatorMode.inactive: if (latestIndicatorBoxExtent <= 0) { return RefreshIndicatorMode.inactive; } else { nextState = RefreshIndicatorMode.drag; } continue drag; drag: case RefreshIndicatorMode.drag: if (latestIndicatorBoxExtent == 0) { return RefreshIndicatorMode.inactive; } else if (latestIndicatorBoxExtent < widget.refreshTriggerPullDistance) { return RefreshIndicatorMode.drag; } else { if (widget.onRefresh != null) { HapticFeedback.mediumImpact(); // Call onRefresh after this frame finished since the function is // user supplied and we're always here in the middle of the sliver's // performLayout. SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) { refreshTask = widget.onRefresh!()..whenComplete(() { if (mounted) { setState(() => refreshTask = null); // Trigger one more transition because by this time, BoxConstraint's // maxHeight might already be resting at 0 in which case no // calls to [transitionNextState] will occur anymore and the // state may be stuck in a non-inactive state. refreshState = transitionNextState(); } }); setState(() => hasSliverLayoutExtent = true); }, debugLabel: 'Refresh.transition'); } return RefreshIndicatorMode.armed; } case RefreshIndicatorMode.armed: if (refreshState == RefreshIndicatorMode.armed && refreshTask == null) { goToDone(); continue done; } if (latestIndicatorBoxExtent > widget.refreshIndicatorExtent) { return RefreshIndicatorMode.armed; } else { nextState = RefreshIndicatorMode.refresh; } continue refresh; refresh: case RefreshIndicatorMode.refresh: if (refreshTask != null) { return RefreshIndicatorMode.refresh; } else { goToDone(); } continue done; done: case RefreshIndicatorMode.done: // Let the transition back to inactive trigger before strictly going // to 0.0 since the last bit of the animation can take some time and // can feel sluggish if not going all the way back to 0.0 prevented // a subsequent pull-to-refresh from starting. if (latestIndicatorBoxExtent > widget.refreshTriggerPullDistance * _inactiveResetOverscrollFraction) { return RefreshIndicatorMode.done; } else { nextState = RefreshIndicatorMode.inactive; } } return nextState; } @override Widget build(BuildContext context) { return _CupertinoSliverRefresh( refreshIndicatorLayoutExtent: widget.refreshIndicatorExtent, hasLayoutExtent: hasSliverLayoutExtent, // A LayoutBuilder lets the sliver's layout changes be fed back out to // its owner to trigger state changes. child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { latestIndicatorBoxExtent = constraints.maxHeight; refreshState = transitionNextState(); if (widget.builder != null && latestIndicatorBoxExtent > 0) { return widget.builder!( context, refreshState, latestIndicatorBoxExtent, widget.refreshTriggerPullDistance, widget.refreshIndicatorExtent, ); } return Container(); }, ), ); } }
flutter/packages/flutter/lib/src/cupertino/refresh.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/cupertino/refresh.dart", "repo_id": "flutter", "token_count": 7598 }
667
// 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/widgets.dart'; import 'colors.dart'; // Please update _TextThemeDefaultsBuilder accordingly after changing the default // color here, as their implementation depends on the default value of the color // field. // // Values derived from https://developer.apple.com/design/resources/. const TextStyle _kDefaultTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemText', fontSize: 17.0, letterSpacing: -0.41, color: CupertinoColors.label, decoration: TextDecoration.none, ); // Please update _TextThemeDefaultsBuilder accordingly after changing the default // color here, as their implementation depends on the default value of the color // field. // // Values derived from https://developer.apple.com/design/resources/. const TextStyle _kDefaultActionTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemText', fontSize: 17.0, letterSpacing: -0.41, color: CupertinoColors.activeBlue, decoration: TextDecoration.none, ); // Please update _TextThemeDefaultsBuilder accordingly after changing the default // color here, as their implementation depends on the default value of the color // field. // // Values derived from https://developer.apple.com/design/resources/. const TextStyle _kDefaultTabLabelTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemText', fontSize: 10.0, fontWeight: FontWeight.w500, letterSpacing: -0.24, color: CupertinoColors.inactiveGray, ); const TextStyle _kDefaultMiddleTitleTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemText', fontSize: 17.0, fontWeight: FontWeight.w600, letterSpacing: -0.41, color: CupertinoColors.label, ); const TextStyle _kDefaultLargeTitleTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemDisplay', fontSize: 34.0, fontWeight: FontWeight.w700, letterSpacing: 0.38, color: CupertinoColors.label, ); // Please update _TextThemeDefaultsBuilder accordingly after changing the default // color here, as their implementation depends on the default value of the color // field. // // Inspected on iOS 13 simulator with "Debug View Hierarchy". // Value extracted from off-center labels. Centered labels have a font size of 25pt. // // The letterSpacing sourced from iOS 14 simulator screenshots for comparison. // See also: // // * https://github.com/flutter/flutter/pull/65501#discussion_r486557093 const TextStyle _kDefaultPickerTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemDisplay', fontSize: 21.0, fontWeight: FontWeight.w400, letterSpacing: -0.6, color: CupertinoColors.label, ); // Please update _TextThemeDefaultsBuilder accordingly after changing the default // color here, as their implementation depends on the default value of the color // field. // // Inspected on iOS 13 simulator with "Debug View Hierarchy". // Value extracted from off-center labels. Centered labels have a font size of 25pt. const TextStyle _kDefaultDateTimePickerTextStyle = TextStyle( inherit: false, fontFamily: 'CupertinoSystemDisplay', fontSize: 21, letterSpacing: 0.4, fontWeight: FontWeight.normal, color: CupertinoColors.label, ); TextStyle? _resolveTextStyle(TextStyle? style, BuildContext context) { // This does not resolve the shadow color, foreground, background, etc. return style?.copyWith( color: CupertinoDynamicColor.maybeResolve(style.color, context), backgroundColor: CupertinoDynamicColor.maybeResolve(style.backgroundColor, context), decorationColor: CupertinoDynamicColor.maybeResolve(style.decorationColor, context), ); } /// Cupertino typography theme in a [CupertinoThemeData]. @immutable class CupertinoTextThemeData with Diagnosticable { /// Create a [CupertinoTextThemeData]. /// /// The [primaryColor] is used to derive TextStyle defaults of other attributes /// such as [navActionTextStyle] and [actionTextStyle]. It must not be null when /// either [navActionTextStyle] or [actionTextStyle] is null. Defaults to /// [CupertinoColors.systemBlue]. /// /// Other [TextStyle] parameters default to default iOS text styles when /// unspecified. const CupertinoTextThemeData({ Color primaryColor = CupertinoColors.systemBlue, TextStyle? textStyle, TextStyle? actionTextStyle, TextStyle? tabLabelTextStyle, TextStyle? navTitleTextStyle, TextStyle? navLargeTitleTextStyle, TextStyle? navActionTextStyle, TextStyle? pickerTextStyle, TextStyle? dateTimePickerTextStyle, }) : this._raw( const _TextThemeDefaultsBuilder(CupertinoColors.label, CupertinoColors.inactiveGray), primaryColor, textStyle, actionTextStyle, tabLabelTextStyle, navTitleTextStyle, navLargeTitleTextStyle, navActionTextStyle, pickerTextStyle, dateTimePickerTextStyle, ); const CupertinoTextThemeData._raw( this._defaults, this._primaryColor, this._textStyle, this._actionTextStyle, this._tabLabelTextStyle, this._navTitleTextStyle, this._navLargeTitleTextStyle, this._navActionTextStyle, this._pickerTextStyle, this._dateTimePickerTextStyle, ) : assert((_navActionTextStyle != null && _actionTextStyle != null) || _primaryColor != null); final _TextThemeDefaultsBuilder _defaults; final Color? _primaryColor; final TextStyle? _textStyle; /// The [TextStyle] of general text content for Cupertino widgets. TextStyle get textStyle => _textStyle ?? _defaults.textStyle; final TextStyle? _actionTextStyle; /// The [TextStyle] of interactive text content such as text in a button without background. TextStyle get actionTextStyle { return _actionTextStyle ?? _defaults.actionTextStyle(primaryColor: _primaryColor); } final TextStyle? _tabLabelTextStyle; /// The [TextStyle] of unselected tabs. TextStyle get tabLabelTextStyle => _tabLabelTextStyle ?? _defaults.tabLabelTextStyle; final TextStyle? _navTitleTextStyle; /// The [TextStyle] of titles in standard navigation bars. TextStyle get navTitleTextStyle => _navTitleTextStyle ?? _defaults.navTitleTextStyle; final TextStyle? _navLargeTitleTextStyle; /// The [TextStyle] of large titles in sliver navigation bars. TextStyle get navLargeTitleTextStyle => _navLargeTitleTextStyle ?? _defaults.navLargeTitleTextStyle; final TextStyle? _navActionTextStyle; /// The [TextStyle] of interactive text content in navigation bars. TextStyle get navActionTextStyle { return _navActionTextStyle ?? _defaults.navActionTextStyle(primaryColor: _primaryColor); } final TextStyle? _pickerTextStyle; /// The [TextStyle] of pickers. TextStyle get pickerTextStyle => _pickerTextStyle ?? _defaults.pickerTextStyle; final TextStyle? _dateTimePickerTextStyle; /// The [TextStyle] of date time pickers. TextStyle get dateTimePickerTextStyle => _dateTimePickerTextStyle ?? _defaults.dateTimePickerTextStyle; /// Returns a copy of the current [CupertinoTextThemeData] with all the colors /// resolved against the given [BuildContext]. /// /// If any of the [InheritedWidget]s required to resolve this /// [CupertinoTextThemeData] is not found in [context], any unresolved /// [CupertinoDynamicColor]s will use the default trait value /// ([Brightness.light] platform brightness, normal contrast, /// [CupertinoUserInterfaceLevelData.base] elevation level). CupertinoTextThemeData resolveFrom(BuildContext context) { return CupertinoTextThemeData._raw( _defaults.resolveFrom(context), CupertinoDynamicColor.maybeResolve(_primaryColor, context), _resolveTextStyle(_textStyle, context), _resolveTextStyle(_actionTextStyle, context), _resolveTextStyle(_tabLabelTextStyle, context), _resolveTextStyle(_navTitleTextStyle, context), _resolveTextStyle(_navLargeTitleTextStyle, context), _resolveTextStyle(_navActionTextStyle, context), _resolveTextStyle(_pickerTextStyle, context), _resolveTextStyle(_dateTimePickerTextStyle, context), ); } /// Returns a copy of the current [CupertinoTextThemeData] instance with /// specified overrides. CupertinoTextThemeData copyWith({ Color? primaryColor, TextStyle? textStyle, TextStyle? actionTextStyle, TextStyle? tabLabelTextStyle, TextStyle? navTitleTextStyle, TextStyle? navLargeTitleTextStyle, TextStyle? navActionTextStyle, TextStyle? pickerTextStyle, TextStyle? dateTimePickerTextStyle, }) { return CupertinoTextThemeData._raw( _defaults, primaryColor ?? _primaryColor, textStyle ?? _textStyle, actionTextStyle ?? _actionTextStyle, tabLabelTextStyle ?? _tabLabelTextStyle, navTitleTextStyle ?? _navTitleTextStyle, navLargeTitleTextStyle ?? _navLargeTitleTextStyle, navActionTextStyle ?? _navActionTextStyle, pickerTextStyle ?? _pickerTextStyle, dateTimePickerTextStyle ?? _dateTimePickerTextStyle, ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const CupertinoTextThemeData defaultData = CupertinoTextThemeData(); properties.add(DiagnosticsProperty<TextStyle>('textStyle', textStyle, defaultValue: defaultData.textStyle)); properties.add(DiagnosticsProperty<TextStyle>('actionTextStyle', actionTextStyle, defaultValue: defaultData.actionTextStyle)); properties.add(DiagnosticsProperty<TextStyle>('tabLabelTextStyle', tabLabelTextStyle, defaultValue: defaultData.tabLabelTextStyle)); properties.add(DiagnosticsProperty<TextStyle>('navTitleTextStyle', navTitleTextStyle, defaultValue: defaultData.navTitleTextStyle)); properties.add(DiagnosticsProperty<TextStyle>('navLargeTitleTextStyle', navLargeTitleTextStyle, defaultValue: defaultData.navLargeTitleTextStyle)); properties.add(DiagnosticsProperty<TextStyle>('navActionTextStyle', navActionTextStyle, defaultValue: defaultData.navActionTextStyle)); properties.add(DiagnosticsProperty<TextStyle>('pickerTextStyle', pickerTextStyle, defaultValue: defaultData.pickerTextStyle)); properties.add(DiagnosticsProperty<TextStyle>('dateTimePickerTextStyle', dateTimePickerTextStyle, defaultValue: defaultData.dateTimePickerTextStyle)); } @override bool operator == (Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is CupertinoTextThemeData && other._defaults == _defaults && other._primaryColor == _primaryColor && other._textStyle == _textStyle && other._actionTextStyle == _actionTextStyle && other._tabLabelTextStyle == _tabLabelTextStyle && other._navTitleTextStyle == _navTitleTextStyle && other._navLargeTitleTextStyle == _navLargeTitleTextStyle && other._navActionTextStyle == _navActionTextStyle && other._pickerTextStyle == _pickerTextStyle && other._dateTimePickerTextStyle == _dateTimePickerTextStyle; } @override int get hashCode => Object.hash( _defaults, _primaryColor, _textStyle, _actionTextStyle, _tabLabelTextStyle, _navTitleTextStyle, _navLargeTitleTextStyle, _navActionTextStyle, _pickerTextStyle, _dateTimePickerTextStyle, ); } @immutable class _TextThemeDefaultsBuilder { const _TextThemeDefaultsBuilder( this.labelColor, this.inactiveGrayColor, ); final Color labelColor; final Color inactiveGrayColor; static TextStyle _applyLabelColor(TextStyle original, Color color) { return original.color == color ? original : original.copyWith(color: color); } TextStyle get textStyle => _applyLabelColor(_kDefaultTextStyle, labelColor); TextStyle get tabLabelTextStyle => _applyLabelColor(_kDefaultTabLabelTextStyle, inactiveGrayColor); TextStyle get navTitleTextStyle => _applyLabelColor(_kDefaultMiddleTitleTextStyle, labelColor); TextStyle get navLargeTitleTextStyle => _applyLabelColor(_kDefaultLargeTitleTextStyle, labelColor); TextStyle get pickerTextStyle => _applyLabelColor(_kDefaultPickerTextStyle, labelColor); TextStyle get dateTimePickerTextStyle => _applyLabelColor(_kDefaultDateTimePickerTextStyle, labelColor); TextStyle actionTextStyle({ Color? primaryColor }) => _kDefaultActionTextStyle.copyWith(color: primaryColor); TextStyle navActionTextStyle({ Color? primaryColor }) => actionTextStyle(primaryColor: primaryColor); _TextThemeDefaultsBuilder resolveFrom(BuildContext context) { final Color resolvedLabelColor = CupertinoDynamicColor.resolve(labelColor, context); final Color resolvedInactiveGray = CupertinoDynamicColor.resolve(inactiveGrayColor, context); return resolvedLabelColor == labelColor && resolvedInactiveGray == CupertinoColors.inactiveGray ? this : _TextThemeDefaultsBuilder(resolvedLabelColor, resolvedInactiveGray); } @override bool operator == (Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is _TextThemeDefaultsBuilder && other.labelColor == labelColor && other.inactiveGrayColor == inactiveGrayColor; } @override int get hashCode => Object.hash(labelColor, inactiveGrayColor); }
flutter/packages/flutter/lib/src/cupertino/text_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/cupertino/text_theme.dart", "repo_id": "flutter", "token_count": 4207 }
668
// 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. // Examples can assume: // class Cat { } /// A category with which to annotate a class, for documentation /// purposes. /// /// A category is usually represented as a section and a subsection, each /// of which is a string. The engineering team that owns the library to which /// the class belongs defines the categories used for classes in that library. /// For example, the Flutter engineering team has defined categories like /// "Basic/Buttons" and "Material Design/Buttons" for Flutter widgets. /// /// A class can have multiple categories. /// /// {@tool snippet} /// /// ```dart /// /// A copper coffee pot, as desired by Ben Turpin. /// /// ...documentation... /// @Category(<String>['Pots', 'Coffee']) /// @Category(<String>['Copper', 'Cookware']) /// @DocumentationIcon('https://example.com/images/coffee.png') /// @Summary('A proper cup of coffee is made in a proper copper coffee pot.') /// class CopperCoffeePot { /// // ...code... /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [DocumentationIcon], which is used to give the URL to an image that /// represents the class. /// * [Summary], which is used to provide a one-line description of a /// class that overrides the inline documentations' own description. class Category { /// Create an annotation to provide a categorization of a class. const Category(this.sections); /// The strings the correspond to the section and subsection of the /// category represented by this object. /// /// By convention, this list usually has two items. The allowed values /// are defined by the team that owns the library to which the annotated /// class belongs. final List<String> sections; } /// A class annotation to provide a URL to an image that represents the class. /// /// Each class should only have one [DocumentationIcon]. /// /// {@tool snippet} /// /// ```dart /// /// Utility class for beginning a dream-sharing sequence. /// /// ...documentation... /// @Category(<String>['Military Technology', 'Experimental']) /// @DocumentationIcon('https://docs.example.org/icons/top.png') /// class DreamSharing { /// // ...code... /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [Category], to help place the class in an index. /// * [Summary], which is used to provide a one-line description of a /// class that overrides the inline documentations' own description. class DocumentationIcon { /// Create an annotation to provide a URL to an image describing a class. const DocumentationIcon(this.url); /// The URL to an image that represents the annotated class. final String url; } /// An annotation that provides a short description of a class for use /// in an index. /// /// Usually the first paragraph of the documentation for a class can be used /// for this purpose, but on occasion the first paragraph is either too short /// or too long for use in isolation, without the remainder of the documentation. /// /// {@tool snippet} /// /// ```dart /// /// A famous cat. /// /// /// /// Instances of this class can hunt small animals. /// /// This cat has three legs. /// @Category(<String>['Animals', 'Cats']) /// @Category(<String>['Cute', 'Pets']) /// @DocumentationIcon('https://www.examples.net/docs/images/icons/pillar.jpeg') /// @Summary('A famous three-legged cat.') /// class Pillar extends Cat { /// // ...code... /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [Category], to help place the class in an index. /// * [DocumentationIcon], which is used to give the URL to an image that /// represents the class. class Summary { /// Create an annotation to provide a short description of a class. const Summary(this.text); /// The text of the summary of the annotated class. final String text; }
flutter/packages/flutter/lib/src/foundation/annotations.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/foundation/annotations.dart", "repo_id": "flutter", "token_count": 1074 }
669
// 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:meta/meta.dart'; // This file gets mutated by //dev/devicelab/bin/tasks/flutter_test_performance.dart // during device lab performance tests. When editing this file, check to make sure // that it didn't break that test. /// Deprecated. Unused by the framework and will be removed in a future version /// of Flutter. If needed, inline any required functionality of this class /// directly in the subclass. /// /// An abstract node in a tree. /// /// AbstractNode has as notion of depth, attachment, and parent, but does not /// have a model for children. /// /// When a subclass is changing the parent of a child, it should call either /// `parent.adoptChild(child)` or `parent.dropChild(child)` as appropriate. /// Subclasses can expose an API for manipulating the tree if desired (e.g. a /// setter for a `child` property, or an `add()` method to manipulate a list). /// /// The current parent node is exposed by the [parent] property. /// /// The current attachment state is exposed by [attached]. The root of any tree /// that is to be considered attached should be manually attached by calling /// [attach]. Other than that, the [attach] and [detach] methods should not be /// called directly; attachment is managed automatically by the aforementioned /// [adoptChild] and [dropChild] methods. /// /// Subclasses that have children must override [attach] and [detach] as /// described in the documentation for those methods. /// /// Nodes always have a [depth] greater than their ancestors'. There's no /// guarantee regarding depth between siblings. The depth of a node is used to /// ensure that nodes are processed in depth order. The [depth] of a child can /// be more than one greater than the [depth] of the parent, because the [depth] /// values are never decreased: all that matters is that it's greater than the /// parent. Consider a tree with a root node A, a child B, and a grandchild C. /// Initially, A will have [depth] 0, B [depth] 1, and C [depth] 2. If C is /// moved to be a child of A, sibling of B, then the numbers won't change. C's /// [depth] will still be 2. The [depth] is automatically maintained by the /// [adoptChild] and [dropChild] methods. @Deprecated( 'If needed, inline any required functionality of AbstractNode in your class directly. ' 'This feature was deprecated after v3.12.0-4.0.pre.', ) class AbstractNode { /// The depth of this node in the tree. /// /// The depth of nodes in a tree monotonically increases as you traverse down /// the tree. int get depth => _depth; int _depth = 0; /// Adjust the [depth] of the given [child] to be greater than this node's own /// [depth]. /// /// Only call this method from overrides of [redepthChildren]. @protected void redepthChild(AbstractNode child) { assert(child.owner == owner); if (child._depth <= _depth) { child._depth = _depth + 1; child.redepthChildren(); } } /// Adjust the [depth] of this node's children, if any. /// /// Override this method in subclasses with child nodes to call [redepthChild] /// for each child. Do not call this method directly. void redepthChildren() { } /// The owner for this node (null if unattached). /// /// The entire subtree that this node belongs to will have the same owner. Object? get owner => _owner; Object? _owner; /// Whether this node is in a tree whose root is attached to something. /// /// This becomes true during the call to [attach]. /// /// This becomes false during the call to [detach]. bool get attached => _owner != null; /// Mark this node as attached to the given owner. /// /// Typically called only from the [parent]'s [attach] method, and by the /// [owner] to mark the root of a tree as attached. /// /// Subclasses with children should override this method to /// [attach] all their children to the same [owner] /// after calling the inherited method, as in `super.attach(owner)`. @mustCallSuper void attach(covariant Object owner) { assert(_owner == null); _owner = owner; } /// Mark this node as detached. /// /// Typically called only from the [parent]'s [detach], and by the [owner] to /// mark the root of a tree as detached. /// /// Subclasses with children should override this method to /// [detach] all their children after calling the inherited method, /// as in `super.detach()`. @mustCallSuper void detach() { assert(_owner != null); _owner = null; assert(parent == null || attached == parent!.attached); } /// The parent of this node in the tree. AbstractNode? get parent => _parent; AbstractNode? _parent; /// Mark the given node as being a child of this node. /// /// Subclasses should call this function when they acquire a new child. @protected @mustCallSuper void adoptChild(covariant AbstractNode child) { assert(child._parent == null); assert(() { AbstractNode node = this; while (node.parent != null) { node = node.parent!; } assert(node != child); // indicates we are about to create a cycle return true; }()); child._parent = this; if (attached) { child.attach(_owner!); } redepthChild(child); } /// Disconnect the given node from this node. /// /// Subclasses should call this function when they lose a child. @protected @mustCallSuper void dropChild(covariant AbstractNode child) { assert(child._parent == this); assert(child.attached == attached); child._parent = null; if (attached) { child.detach(); } } }
flutter/packages/flutter/lib/src/foundation/node.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/foundation/node.dart", "repo_id": "flutter", "token_count": 1673 }
670