text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// ignore_for_file: unused_field import 'package:flutter/material.dart'; // #docregion BubblePainterEmpty @immutable class BubbleBackground extends StatelessWidget { const BubbleBackground({ super.key, required this.colors, this.child, }); final List<Color> colors; final Widget? child; @override Widget build(BuildContext context) { return CustomPaint( painter: BubblePainter( colors: colors, ), child: child, ); } } class BubblePainter extends CustomPainter { BubblePainter({ required List<Color> colors, }) : _colors = colors; final List<Color> _colors; @override void paint(Canvas canvas, Size size) { // TODO: } @override bool shouldRepaint(BubblePainter oldDelegate) { // TODO: return false; } } // #enddocregion BubblePainterEmpty
website/examples/cookbook/effects/gradient_bubbles/lib/bubble_painter_empty.dart/0
{ "file_path": "website/examples/cookbook/effects/gradient_bubbles/lib/bubble_painter_empty.dart", "repo_id": "website", "token_count": 306 }
1,254
import 'package:flutter/material.dart'; // #docregion GlobalKey @immutable class LocationListItem extends StatelessWidget { final GlobalKey _backgroundImageKey = GlobalKey(); Widget _buildParallaxBackground(BuildContext context) { return Flow( delegate: ParallaxFlowDelegate( scrollable: Scrollable.of(context), listItemContext: context, backgroundImageKey: _backgroundImageKey, ), children: [ Image.network( imageUrl, key: _backgroundImageKey, fit: BoxFit.cover, ), ], ); } // code-excerpt-closing-bracket // #enddocregion GlobalKey LocationListItem({ super.key, required this.imageUrl, required this.name, required this.country, }); final String imageUrl; final String name; final String country; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), child: AspectRatio( aspectRatio: 16 / 9, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: Stack( children: [ _buildParallaxBackground(context), _buildGradient(), _buildTitleAndSubtitle(), ], ), ), ), ); } Widget _buildGradient() { return Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.transparent, Colors.black.withOpacity(0.7)], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: const [0.6, 0.95], ), ), ), ); } Widget _buildTitleAndSubtitle() { return Positioned( left: 20, bottom: 20, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( name, style: const TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), Text( country, style: const TextStyle( color: Colors.white, fontSize: 14, ), ), ], ), ); } } // #docregion ParallaxFlowDelegateGK class ParallaxFlowDelegate extends FlowDelegate { ParallaxFlowDelegate({ required this.scrollable, required this.listItemContext, required this.backgroundImageKey, }); final ScrollableState scrollable; final BuildContext listItemContext; final GlobalKey backgroundImageKey; // code-excerpt-closing-bracket // #enddocregion ParallaxFlowDelegateGK @override BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) { return BoxConstraints.tightFor( width: constraints.maxWidth, ); } // #docregion PaintChildren // #docregion PaintChildrenPt2 // #docregion PaintChildrenPt3 // #docregion PaintChildrenPt4 // #docregion PaintChildrenPt5 @override void paintChildren(FlowPaintingContext context) { // Calculate the position of this list item within the viewport. final scrollableBox = scrollable.context.findRenderObject() as RenderBox; final listItemBox = listItemContext.findRenderObject() as RenderBox; final listItemOffset = listItemBox.localToGlobal( listItemBox.size.centerLeft(Offset.zero), ancestor: scrollableBox); // code-excerpt-closing-bracket // #enddocregion PaintChildren // Determine the percent position of this list item within the // scrollable area. final viewportDimension = scrollable.position.viewportDimension; final scrollFraction = (listItemOffset.dy / viewportDimension).clamp(0.0, 1.0); // code-excerpt-closing-bracket // #enddocregion PaintChildrenPt2 // Calculate the vertical alignment of the background // based on the scroll percent. final verticalAlignment = Alignment(0.0, scrollFraction * 2 - 1); // code-excerpt-closing-bracket // #enddocregion PaintChildrenPt3 // Convert the background alignment into a pixel offset for // painting purposes. final backgroundSize = (backgroundImageKey.currentContext!.findRenderObject() as RenderBox) .size; final listItemSize = context.size; final childRect = verticalAlignment.inscribe(backgroundSize, Offset.zero & listItemSize); // code-excerpt-closing-bracket // #enddocregion PaintChildrenPt4 // Paint the background. context.paintChild( 0, transform: Transform.translate(offset: Offset(0.0, childRect.top)).transform, ); // code-excerpt-closing-bracket // #enddocregion PaintChildrenPt5 } @override bool shouldRepaint(ParallaxFlowDelegate oldDelegate) { return scrollable != oldDelegate.scrollable || listItemContext != oldDelegate.listItemContext || backgroundImageKey != oldDelegate.backgroundImageKey; } } class ParallaxRecipe extends StatelessWidget { const ParallaxRecipe({super.key}); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Column( children: [ for (final location in locations) LocationListItem( imageUrl: location.imageUrl, name: location.name, country: location.place, ), ], ), ); } } class Location { const Location({ required this.name, required this.place, required this.imageUrl, }); final String name; final String place; final String imageUrl; } const urlPrefix = 'https://docs.flutter.dev/cookbook/img-files/effects/parallax'; const locations = [ Location( name: 'Mount Rushmore', place: 'U.S.A', imageUrl: '$urlPrefix/01-mount-rushmore.jpg', ), Location( name: 'Gardens By The Bay', place: 'Singapore', imageUrl: '$urlPrefix/02-singapore.jpg', ), Location( name: 'Machu Picchu', place: 'Peru', imageUrl: '$urlPrefix/03-machu-picchu.jpg', ), Location( name: 'Vitznau', place: 'Switzerland', imageUrl: '$urlPrefix/04-vitznau.jpg', ), Location( name: 'Bali', place: 'Indonesia', imageUrl: '$urlPrefix/05-bali.jpg', ), Location( name: 'Mexico City', place: 'Mexico', imageUrl: '$urlPrefix/06-mexico-city.jpg', ), Location( name: 'Cairo', place: 'Egypt', imageUrl: '$urlPrefix/07-cairo.jpg', ), ];
website/examples/cookbook/effects/parallax_scrolling/lib/excerpt5.dart/0
{ "file_path": "website/examples/cookbook/effects/parallax_scrolling/lib/excerpt5.dart", "repo_id": "website", "token_count": 2714 }
1,255
// ignore_for_file: unused_element import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import './excerpt1.dart'; import './excerpt3.dart'; // #docregion AnimationController class _TypingIndicatorState extends State<TypingIndicator> with TickerProviderStateMixin { late AnimationController _appearanceController; late Animation<double> _indicatorSpaceAnimation; late Animation<double> _smallBubbleAnimation; late Animation<double> _mediumBubbleAnimation; late Animation<double> _largeBubbleAnimation; late AnimationController _repeatingController; final List<Interval> _dotIntervals = const [ Interval(0.25, 0.8), Interval(0.35, 0.9), Interval(0.45, 1.0), ]; @override void initState() { super.initState(); // other initializations... _repeatingController = AnimationController( vsync: this, duration: const Duration(milliseconds: 1500), ); if (widget.showIndicator) { _showIndicator(); } } @override void dispose() { _appearanceController.dispose(); _repeatingController.dispose(); super.dispose(); } void _showIndicator() { _appearanceController ..duration = const Duration(milliseconds: 750) ..forward(); _repeatingController.repeat(); // <-- Add this } void _hideIndicator() { _appearanceController ..duration = const Duration(milliseconds: 150) ..reverse(); _repeatingController.stop(); // <-- Add this } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _indicatorSpaceAnimation, builder: (context, child) { return SizedBox( height: _indicatorSpaceAnimation.value, child: child, ); }, child: Stack( children: [ AnimatedBubble( animation: _smallBubbleAnimation, left: 8, bottom: 8, bubble: CircleBubble( size: 8, bubbleColor: widget.bubbleColor, ), ), AnimatedBubble( animation: _mediumBubbleAnimation, left: 10, bottom: 10, bubble: CircleBubble( size: 16, bubbleColor: widget.bubbleColor, ), ), AnimatedBubble( animation: _largeBubbleAnimation, left: 12, bottom: 12, bubble: StatusBubble( repeatingController: _repeatingController, // <-- Add this dotIntervals: _dotIntervals, flashingCircleDarkColor: widget.flashingCircleDarkColor, flashingCircleBrightColor: widget.flashingCircleBrightColor, bubbleColor: widget.bubbleColor, ), ), ], ), ); } } class StatusBubble extends StatelessWidget { const StatusBubble({ super.key, required this.repeatingController, required this.dotIntervals, required this.flashingCircleBrightColor, required this.flashingCircleDarkColor, required this.bubbleColor, }); final AnimationController repeatingController; final List<Interval> dotIntervals; final Color flashingCircleDarkColor; final Color flashingCircleBrightColor; final Color bubbleColor; @override Widget build(BuildContext context) { return Container( width: 85, height: 44, padding: const EdgeInsets.symmetric(horizontal: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(27), color: bubbleColor, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ FlashingCircle( index: 0, repeatingController: repeatingController, dotIntervals: dotIntervals, flashingCircleDarkColor: flashingCircleDarkColor, flashingCircleBrightColor: flashingCircleBrightColor, ), FlashingCircle( index: 1, repeatingController: repeatingController, dotIntervals: dotIntervals, flashingCircleDarkColor: flashingCircleDarkColor, flashingCircleBrightColor: flashingCircleBrightColor, ), FlashingCircle( index: 2, repeatingController: repeatingController, dotIntervals: dotIntervals, flashingCircleDarkColor: flashingCircleDarkColor, flashingCircleBrightColor: flashingCircleBrightColor, ), ], ), ); } } class FlashingCircle extends StatelessWidget { const FlashingCircle({ super.key, required this.index, required this.repeatingController, required this.dotIntervals, required this.flashingCircleBrightColor, required this.flashingCircleDarkColor, }); final int index; final AnimationController repeatingController; final List<Interval> dotIntervals; final Color flashingCircleDarkColor; final Color flashingCircleBrightColor; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: repeatingController, builder: (context, child) { final circleFlashPercent = dotIntervals[index].transform( repeatingController.value, ); final circleColorPercent = sin(pi * circleFlashPercent); return Container( width: 12, height: 12, decoration: BoxDecoration( shape: BoxShape.circle, color: Color.lerp( flashingCircleDarkColor, flashingCircleBrightColor, circleColorPercent, ), ), ); }, ); } } // #enddocregion AnimationController
website/examples/cookbook/effects/typing_indicator/lib/excerpt4.dart/0
{ "file_path": "website/examples/cookbook/effects/typing_indicator/lib/excerpt4.dart", "repo_id": "website", "token_count": 2405 }
1,256
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Retrieve Text Input', home: MyCustomForm(), ); } } // Define a custom Form widget. class MyCustomForm extends StatefulWidget { const MyCustomForm({super.key}); @override State<MyCustomForm> createState() => _MyCustomFormState(); } // Define a corresponding State class. // This class holds data related to the Form. class _MyCustomFormState extends State<MyCustomForm> { // Create a text controller and use it to retrieve the current value // of the TextField. final myController = TextEditingController(); // #docregion initState @override void initState() { super.initState(); // Start listening to changes. myController.addListener(_printLatestValue); } // #enddocregion initState // #docregion dispose @override void dispose() { // Clean up the controller when the widget is removed from the widget tree. // This also removes the _printLatestValue listener. myController.dispose(); super.dispose(); } // #enddocregion dispose // #docregion printLatestValue void _printLatestValue() { final text = myController.text; print('Second text field: $text (${text.characters.length})'); } // #enddocregion printLatestValue @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Retrieve Text Input'), ), body: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ // #docregion TextField1 TextField( onChanged: (text) { print('First text field: $text (${text.characters.length})'); }, ), // #enddocregion TextField1 // #docregion TextField2 TextField( controller: myController, ), // #enddocregion TextField2 ], ), ), ); } }
website/examples/cookbook/forms/text_field_changes/lib/main.dart/0
{ "file_path": "website/examples/cookbook/forms/text_field_changes/lib/main.dart", "repo_id": "website", "token_count": 822 }
1,257
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: return macos; case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions web = FirebaseOptions( apiKey: 'blahblahbla', appId: '1:123456:web:blahblahbla', messagingSenderId: '123456', projectId: 'card-game-deadbeef', authDomain: 'card-game-deadbeef.firebaseapp.com', storageBucket: 'card-game-deadbeef.appspot.com', ); static const FirebaseOptions android = FirebaseOptions( apiKey: 'blahblahbla', appId: '1:123456:android:blahblahbla', messagingSenderId: '123456', projectId: 'card-game-deadbeef', storageBucket: 'card-game-deadbeef.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'blahblahbla', appId: '1:123456:ios:blahblahbla', messagingSenderId: '123456', projectId: 'card-game-deadbeef', storageBucket: 'card-game-deadbeef.appspot.com', iosBundleId: 'com.example.card', ); static const FirebaseOptions macos = FirebaseOptions( apiKey: 'blahblahbla', appId: '1:123456:ios:blahblahbla', messagingSenderId: '123456', projectId: 'card-game-deadbeef', storageBucket: 'card-game-deadbeef.appspot.com', iosBundleId: 'com.example.card.RunnerTests', ); }
website/examples/cookbook/games/firestore_multiplayer/lib/firebase_options.dart/0
{ "file_path": "website/examples/cookbook/games/firestore_multiplayer/lib/firebase_options.dart", "repo_id": "website", "token_count": 1001 }
1,258
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Basic List'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: const Text(title), ), // #docregion ListView body: ListView( children: const <Widget>[ ListTile( leading: Icon(Icons.map), title: Text('Map'), ), ListTile( leading: Icon(Icons.photo_album), title: Text('Album'), ), ListTile( leading: Icon(Icons.phone), title: Text('Phone'), ), ], ), // #enddocregion ListView ), ); } }
website/examples/cookbook/lists/basic_list/lib/main.dart/0
{ "file_path": "website/examples/cookbook/lists/basic_list/lib/main.dart", "repo_id": "website", "token_count": 454 }
1,259
import 'package:flutter/material.dart'; class FirstScreen extends StatelessWidget { const FirstScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('First Screen'), ), body: Center( child: ElevatedButton( onPressed: () { // Navigate to the second screen when tapped. }, child: const Text('Launch screen'), ), ), ); } } class SecondScreen extends StatelessWidget { const SecondScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Screen'), ), body: Center( child: ElevatedButton( onPressed: () { // Navigate back to first screen when tapped. }, child: const Text('Go back!'), ), ), ); } }
website/examples/cookbook/navigation/named_routes/lib/main_original.dart/0
{ "file_path": "website/examples/cookbook/navigation/named_routes/lib/main_original.dart", "repo_id": "website", "token_count": 408 }
1,260
import 'dart:io'; import 'package:flutter/widgets.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; class MyBannerAdWidget extends StatefulWidget { /// The requested size of the banner. Defaults to [AdSize.banner]. final AdSize adSize; /// The AdMob ad unit to show. /// /// TODO: replace this test ad unit with your own ad unit // #docregion adUnitId final String adUnitId = Platform.isAndroid // Use this ad unit on Android... ? 'ca-app-pub-3940256099942544/6300978111' // ... or this one on iOS. : 'ca-app-pub-3940256099942544/2934735716'; // #enddocregion adUnitId MyBannerAdWidget({ super.key, this.adSize = AdSize.banner, }); @override State<MyBannerAdWidget> createState() => _MyBannerAdWidgetState(); } class _MyBannerAdWidgetState extends State<MyBannerAdWidget> { /// The banner ad to show. This is `null` until the ad is actually loaded. BannerAd? _bannerAd; // #docregion build @override Widget build(BuildContext context) { return SafeArea( child: SizedBox( width: widget.adSize.width.toDouble(), height: widget.adSize.height.toDouble(), child: _bannerAd == null // Nothing to render yet. ? SizedBox() // The actual ad. : AdWidget(ad: _bannerAd!), ), ); } // #enddocregion build @override void initState() { super.initState(); _loadAd(); } @override void dispose() { // #docregion dispose _bannerAd?.dispose(); // #enddocregion dispose super.dispose(); } // #docregion loadAd /// Loads a banner ad. void _loadAd() { final bannerAd = BannerAd( size: widget.adSize, adUnitId: widget.adUnitId, request: const AdRequest(), listener: BannerAdListener( // Called when an ad is successfully received. onAdLoaded: (ad) { if (!mounted) { ad.dispose(); return; } setState(() { _bannerAd = ad as BannerAd; }); }, // Called when an ad request failed. onAdFailedToLoad: (ad, error) { debugPrint('BannerAd failed to load: $error'); ad.dispose(); }, ), ); // Start loading. bannerAd.load(); } // #enddocregion loadAd }
website/examples/cookbook/plugins/google_mobile_ads/lib/my_banner_ad.dart/0
{ "file_path": "website/examples/cookbook/plugins/google_mobile_ads/lib/my_banner_ad.dart", "repo_id": "website", "token_count": 991 }
1,261
name: introduction description: A new Flutter project. publish_to: none # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter integration_test: sdk: flutter flutter_test: sdk: flutter dev_dependencies: example_utils: path: ../../../../example_utils test: any flutter: uses-material-design: true
website/examples/cookbook/testing/integration/introduction/pubspec.yaml/0
{ "file_path": "website/examples/cookbook/testing/integration/introduction/pubspec.yaml", "repo_id": "website", "token_count": 154 }
1,262
// Mocks generated by Mockito 5.4.4 from annotations // in mocking/test/fetch_album_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i5; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { _FakeResponse_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { _FakeStreamedResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [Client]. /// /// See the documentation for Mockito's code generation for more information. class MockClient extends _i1.Mock implements _i2.Client { MockClient() { _i1.throwOnMissingStub(this); } @override _i3.Future<_i2.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i3.Future<_i2.Response>); @override _i3.Future<_i2.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i3.Future<_i2.Response>); @override _i3.Future<_i2.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i4.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i3.Future<_i2.Response>); @override _i3.Future<_i2.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i4.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i3.Future<_i2.Response>); @override _i3.Future<_i2.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i4.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i3.Future<_i2.Response>); @override _i3.Future<_i2.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i4.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i3.Future<_i2.Response>); @override _i3.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i3.Future<String>.value(_i5.dummyValue<String>( this, Invocation.method( #read, [url], {#headers: headers}, ), )), ) as _i3.Future<String>); @override _i3.Future<_i6.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i3.Future<_i6.Uint8List>); @override _i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i3.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( this, Invocation.method( #send, [request], ), )), ) as _i3.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); }
website/examples/cookbook/testing/unit/mocking/test/fetch_album_test.mocks.dart/0
{ "file_path": "website/examples/cookbook/testing/unit/mocking/test/fetch_album_test.mocks.dart", "repo_id": "website", "token_count": 3600 }
1,263
name: finders description: A new Flutter project. environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/cookbook/testing/widget/tap_drag/pubspec.yaml/0
{ "file_path": "website/examples/cookbook/testing/widget/tap_drag/pubspec.yaml", "repo_id": "website", "token_count": 105 }
1,264
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'address.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Address _$AddressFromJson(Map<String, dynamic> json) => Address( json['street'] as String, json['city'] as String, ); Map<String, dynamic> _$AddressToJson(Address instance) => <String, dynamic>{ 'street': instance.street, 'city': instance.city, };
website/examples/development/data-and-backend/json/lib/nested/address.g.dart/0
{ "file_path": "website/examples/development/data-and-backend/json/lib/nested/address.g.dart", "repo_id": "website", "token_count": 154 }
1,265
// ignore_for_file: avoid_print // #docregion UseApi import 'generated_pigeon.dart'; Future<void> onClick() async { SearchRequest request = SearchRequest(query: 'test'); Api api = SomeApi(); SearchReply reply = await api.search(request); print('reply: ${reply.result}'); } // #enddocregion UseApi class SomeApi extends Api {}
website/examples/development/platform_integration/lib/use_pigeon.dart/0
{ "file_path": "website/examples/development/platform_integration/lib/use_pigeon.dart", "repo_id": "website", "token_count": 113 }
1,266
import 'package:flutter/material.dart'; // TapboxA manages its own state. //------------------------- TapboxA ---------------------------------- class TapboxA extends StatefulWidget { const TapboxA({super.key}); @override State<TapboxA> createState() => _TapboxAState(); } class _TapboxAState extends State<TapboxA> { bool _active = false; void _handleTap() { setState(() { _active = !_active; }); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _handleTap, child: Container( width: 200, height: 200, decoration: BoxDecoration( color: _active ? Colors.lightGreen[700] : Colors.grey[600], ), child: Center( child: Text( _active ? 'Active' : 'Inactive', style: const TextStyle(fontSize: 32, color: Colors.white), ), ), ), ); } } //------------------------- MyApp ---------------------------------- class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: AppBar( title: const Text('Flutter Demo'), ), body: const Center( child: TapboxA(), ), ), ); } }
website/examples/development/ui/interactive/lib/self_managed.dart/0
{ "file_path": "website/examples/development/ui/interactive/lib/self_managed.dart", "repo_id": "website", "token_count": 558 }
1,267
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State<SampleAppPage> createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { List widgets = []; @override void initState() { super.initState(); loadData(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample App'), ), body: ListView.builder( itemCount: widgets.length, itemBuilder: (context, position) { return getRow(position); }, ), ); } Widget getRow(int i) { return Padding( padding: const EdgeInsets.all(10), child: Text("Row ${widgets[i]["title"]}"), ); } // #docregion loadData Future<void> loadData() async { var dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts'); http.Response response = await http.get(dataURL); setState(() { widgets = jsonDecode(response.body); }); } // #enddocregion loadData }
website/examples/get-started/flutter-for/android_devs/lib/async.dart/0
{ "file_path": "website/examples/get-started/flutter-for/android_devs/lib/async.dart", "repo_id": "website", "token_count": 598 }
1,268
import 'package:flutter/material.dart'; void main() => runApp(const MaterialApp(home: DemoApp())); class DemoApp extends StatelessWidget { const DemoApp({super.key}); @override Widget build(BuildContext context) => const Scaffold(body: Signature()); } class Signature extends StatefulWidget { const Signature({super.key}); @override State<Signature> createState() => SignatureState(); } class SignatureState extends State<Signature> { List<Offset?> _points = <Offset?>[]; @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: (details) { setState(() { RenderBox? referenceBox = context.findRenderObject() as RenderBox; Offset localPosition = referenceBox.globalToLocal(details.globalPosition); _points = List.from(_points)..add(localPosition); }); }, onPanEnd: (details) => _points.add(null), child: // #docregion CustomPaint CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), // #enddocregion CustomPaint ); } } // #docregion CustomPainter class SignaturePainter extends CustomPainter { SignaturePainter(this.points); final List<Offset?> points; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; } // #enddocregion CustomPainter
website/examples/get-started/flutter-for/ios_devs/lib/canvas.dart/0
{ "file_path": "website/examples/get-started/flutter-for/ios_devs/lib/canvas.dart", "repo_id": "website", "token_count": 669 }
1,269
import 'package:flutter/material.dart'; class MyWidget extends StatelessWidget { const MyWidget({super.key}); // #docregion CustomFont @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample App'), ), body: const Center( child: Text( 'This is a custom font text', style: TextStyle(fontFamily: 'MyCustomFont'), ), ), ); } // #enddocregion CustomFont }
website/examples/get-started/flutter-for/ios_devs/lib/text.dart/0
{ "file_path": "website/examples/get-started/flutter-for/ios_devs/lib/text.dart", "repo_id": "website", "token_count": 200 }
1,270
// ignore_for_file: avoid_print, unused_local_variable, prefer_typing_uninitialized_variables // #docregion Main /// Dart void main() {} // #enddocregion Main void printCode() { // #docregion Print /// Dart print('Hello world!'); // #enddocregion Print } void variableCode() { // #docregion Variables /// Dart /// Both variables are acceptable. String name = 'dart'; // Explicitly typed as a [String]. var otherName = 'Dart'; // Inferred [String] type. // #enddocregion Variables } void nullCode() { // #docregion Null // Dart var name; // == null; raises a linter warning int? x; // == null // #enddocregion Null } void trueExample() { // #docregion True /// Dart var myNull; var zero = 0; if (zero == 0) { print('use "== 0" to check zero'); } // #enddocregion True } // #docregion Function /// Dart /// You can explicitly define the return type. bool fn() { return true; } // #enddocregion Function
website/examples/get-started/flutter-for/react_native_devs/lib/main.dart/0
{ "file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/main.dart", "repo_id": "website", "token_count": 318 }
1,271
import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: DemoApp())); } class DemoApp extends StatelessWidget { const DemoApp({super.key}); @override Widget build(BuildContext context) => const Scaffold(body: Signature()); } class Signature extends StatefulWidget { const Signature({super.key}); @override SignatureState createState() => SignatureState(); } class SignatureState extends State<Signature> { List<Offset?> _points = <Offset?>[]; void _onPanUpdate(DragUpdateDetails details) { setState(() { final RenderBox referenceBox = context.findRenderObject() as RenderBox; final Offset localPosition = referenceBox.globalToLocal( details.globalPosition, ); _points = List.from(_points)..add(localPosition); }); } @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: _onPanUpdate, onPanEnd: (details) => _points.add(null), child: CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), ); } } class SignaturePainter extends CustomPainter { const SignaturePainter(this.points); final List<Offset?> points; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; }
website/examples/get-started/flutter-for/xamarin_devs/lib/draw.dart/0
{ "file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/draw.dart", "repo_id": "website", "token_count": 606 }
1,272
import 'package:flutter/material.dart'; // #docregion Localization import 'package:flutter_localizations/flutter_localizations.dart'; class MyWidget extends StatelessWidget { const MyWidget({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( localizationsDelegates: <LocalizationsDelegate<dynamic>>[ // Add app-specific localization delegate[s] here GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: <Locale>[ Locale('en', 'US'), // English Locale('he', 'IL'), // Hebrew // ... other locales the app supports ], ); } } // #enddocregion Localization class TextWidget extends StatelessWidget { const TextWidget({super.key}); @override Widget build(BuildContext context) { // #docregion AccessString return const Text(Strings.welcomeMessage); // #enddocregion AccessString } } // #docregion StringsClass class Strings { static const String welcomeMessage = 'Welcome To Flutter'; } // #enddocregion StringsClass class CustomFontExample extends StatelessWidget { const CustomFontExample({super.key}); // #docregion CustomFont @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: const Center( child: Text( 'This is a custom font text', style: TextStyle(fontFamily: 'MyCustomFont'), ), ), ); } // #enddocregion CustomFont }
website/examples/get-started/flutter-for/xamarin_devs/lib/strings.dart/0
{ "file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/strings.dart", "repo_id": "website", "token_count": 548 }
1,273
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; void examples(BuildContext context) { // #docregion MaterialAppExample const MaterialApp( title: 'Localizations Sample App', localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, ); // #enddocregion MaterialAppExample // #docregion LocaleResolution MaterialApp( localeResolutionCallback: ( locale, supportedLocales, ) { return locale; }, ); // #enddocregion LocaleResolution // #docregion MyLocale Locale myLocale = Localizations.localeOf(context); // #enddocregion MyLocale const MaterialApp( // #docregion SupportedLocales supportedLocales: [ Locale.fromSubtags(languageCode: 'zh'), // generic Chinese 'zh' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans'), // generic simplified Chinese 'zh_Hans' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant'), // generic traditional Chinese 'zh_Hant' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'), // 'zh_Hans_CN' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'), // 'zh_Hant_TW' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'), // 'zh_Hant_HK' ], // #enddocregion SupportedLocales ); } class PageWithDatePicker extends StatefulWidget { const PageWithDatePicker({super.key}); final String title = 'Localizations Sample App'; @override State<PageWithDatePicker> createState() => _PageWithDatePickerState(); } class _PageWithDatePickerState extends State<PageWithDatePicker> { @override // #docregion CalendarDatePicker Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // Add the following code Localizations.override( context: context, locale: const Locale('es'), // Using a Builder to get the correct BuildContext. // Alternatively, you can create a new widget and Localizations.override // will pass the updated BuildContext to the new widget. child: Builder( builder: (context) { // A toy example for an internationalized Material widget. return CalendarDatePicker( initialDate: DateTime.now(), firstDate: DateTime(1900), lastDate: DateTime(2100), onDateChanged: (value) {}, ); }, ), ), ], ), ), ); } // #enddocregion CalendarDatePicker }
website/examples/internationalization/gen_l10n_example/lib/examples.dart/0
{ "file_path": "website/examples/internationalization/gen_l10n_example/lib/examples.dart", "repo_id": "website", "token_count": 1338 }
1,274
import 'package:flutter_test/flutter_test.dart'; import 'package:intl_example/main.dart'; void main() { testWidgets('Test localized strings in demo app', (tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const Demo()); // // Set the app's locale to English await tester.binding.setLocale('en', ''); await tester.pumpAndSettle(); // Verify that our text is English expect(find.text('Hello World'), findsWidgets); expect(find.text('Hola Mundo'), findsNothing); // Set the app's locale to Spanish await tester.binding.setLocale('es', ''); await tester.pumpAndSettle(); // Verify that our text is Spanish expect(find.text('Hola Mundo'), findsWidgets); expect(find.text('Hello World'), findsNothing); }); }
website/examples/internationalization/intl_example/test/widget_test.dart/0
{ "file_path": "website/examples/internationalization/intl_example/test/widget_test.dart", "repo_id": "website", "token_count": 276 }
1,275
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; const double _colorItemHeight = 48; class _Palette { const _Palette({ required this.name, required this.primary, this.accent, this.threshold = 900, }); final String name; final MaterialColor primary; final MaterialAccentColor? accent; // Titles for indices > threshold are white, otherwise black. final int threshold; } const List<_Palette> _allPalettes = [ _Palette( name: 'Red', primary: Colors.red, accent: Colors.redAccent, threshold: 300, ), _Palette( name: 'Pink', primary: Colors.pink, accent: Colors.pinkAccent, threshold: 200, ), _Palette( name: 'Purple', primary: Colors.purple, accent: Colors.purpleAccent, threshold: 200, ), _Palette( name: 'Deep purple', primary: Colors.deepPurple, accent: Colors.deepPurpleAccent, threshold: 200, ), _Palette( name: 'Indigo', primary: Colors.indigo, accent: Colors.indigoAccent, threshold: 200, ), _Palette( name: 'Blue', primary: Colors.blue, accent: Colors.blueAccent, threshold: 400, ), _Palette( name: 'Light blue', primary: Colors.lightBlue, accent: Colors.lightBlueAccent, threshold: 500, ), _Palette( name: 'Cyan', primary: Colors.cyan, accent: Colors.cyanAccent, threshold: 600, ), _Palette( name: 'Teal', primary: Colors.teal, accent: Colors.tealAccent, threshold: 400, ), _Palette( name: 'Green', primary: Colors.green, accent: Colors.greenAccent, threshold: 500, ), _Palette( name: 'Light green', primary: Colors.lightGreen, accent: Colors.lightGreenAccent, threshold: 600, ), _Palette( name: 'Lime', primary: Colors.lime, accent: Colors.limeAccent, threshold: 800, ), _Palette( name: 'Yellow', primary: Colors.yellow, accent: Colors.yellowAccent, ), _Palette( name: 'Amber', primary: Colors.amber, accent: Colors.amberAccent, ), _Palette( name: 'Orange', primary: Colors.orange, accent: Colors.orangeAccent, threshold: 700, ), _Palette( name: 'Deep orange', primary: Colors.deepOrange, accent: Colors.deepOrangeAccent, threshold: 400, ), _Palette( name: 'Brown', primary: Colors.brown, threshold: 200, ), _Palette( name: 'Grey', primary: Colors.grey, threshold: 500, ), _Palette( name: 'Blue grey', primary: Colors.blueGrey, threshold: 500, ), ]; class _ColorItem extends StatelessWidget { const _ColorItem({ required this.index, required this.color, this.prefix = '', }); final int index; final Color color; final String prefix; String get _colorString => "#${color.value.toRadixString(16).padLeft(8, '0').toUpperCase()}"; @override Widget build(BuildContext context) { return Semantics( container: true, child: Container( height: _colorItemHeight, padding: const EdgeInsets.symmetric(horizontal: 16), color: color, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text('$prefix$index'), Flexible(child: Text(_colorString)), ], ), ), ); } } class _PaletteTabView extends StatelessWidget { const _PaletteTabView({required this.colors}); final _Palette colors; static const primaryKeys = <int>[ 50, 100, 200, 300, 400, 500, 600, 700, 800, 900 ]; static const accentKeys = <int>[100, 200, 400, 700]; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final whiteTextStyle = textTheme.bodyMedium!.copyWith( color: Colors.white, ); final blackTextStyle = textTheme.bodyMedium!.copyWith( color: Colors.black, ); return Scrollbar( child: ListView( itemExtent: _colorItemHeight, children: [ for (final key in primaryKeys) DefaultTextStyle( style: key > colors.threshold ? whiteTextStyle : blackTextStyle, child: _ColorItem(index: key, color: colors.primary[key]!), ), if (colors.accent != null) for (final key in accentKeys) DefaultTextStyle( style: key > colors.threshold ? whiteTextStyle : blackTextStyle, child: _ColorItem( index: key, color: colors.accent![key]!, prefix: 'A', ), ), ], ), ); } } class ColorsDemo extends StatelessWidget { const ColorsDemo({super.key}); @override Widget build(BuildContext context) { const palettes = _allPalettes; return MaterialApp( home: DefaultTabController( length: palettes.length, child: Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: const Text('Colors'), bottom: TabBar( isScrollable: true, tabs: [ for (final palette in palettes) Tab(text: palette.name), ], ), ), body: TabBarView( children: [ for (final palette in palettes) _PaletteTabView(colors: palette), ], ), ), ), ); } } void main() { runApp(const ColorsDemo()); }
website/examples/layout/gallery/lib/colors_demo.dart/0
{ "file_path": "website/examples/layout/gallery/lib/colors_demo.dart", "repo_id": "website", "token_count": 2477 }
1,276
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show debugPaintSizeEnabled; void main() { debugPaintSizeEnabled = false; // Set to true for visual layout. runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter layout demo', home: buildHomePage('Strawberry Pavlova Recipe'), ); } Widget buildHomePage(String title) { const titleText = Padding( padding: EdgeInsets.all(20), child: Text( 'Strawberry Pavlova', style: TextStyle( fontWeight: FontWeight.w800, letterSpacing: 0.5, fontSize: 30, ), ), ); const subTitle = Text( 'Pavlova is a meringue-based dessert named after the Russian ballerina ' 'Anna Pavlova. Pavlova features a crisp crust and soft, light inside, ' 'topped with fruit and whipped cream.', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Georgia', fontSize: 25, ), ); // #docregion ratings, stars final stars = Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), const Icon(Icons.star, color: Colors.black), const Icon(Icons.star, color: Colors.black), ], ); // #enddocregion stars final ratings = Container( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ stars, const Text( '170 Reviews', style: TextStyle( color: Colors.black, fontWeight: FontWeight.w800, fontFamily: 'Roboto', letterSpacing: 0.5, fontSize: 20, ), ), ], ), ); // #enddocregion ratings // #docregion iconList const descTextStyle = TextStyle( color: Colors.black, fontWeight: FontWeight.w800, fontFamily: 'Roboto', letterSpacing: 0.5, fontSize: 18, height: 2, ); // DefaultTextStyle.merge() allows you to create a default text // style that is inherited by its child and all subsequent children. final iconList = DefaultTextStyle.merge( style: descTextStyle, child: Container( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ Icon(Icons.kitchen, color: Colors.green[500]), const Text('PREP:'), const Text('25 min'), ], ), Column( children: [ Icon(Icons.timer, color: Colors.green[500]), const Text('COOK:'), const Text('1 hr'), ], ), Column( children: [ Icon(Icons.restaurant, color: Colors.green[500]), const Text('FEEDS:'), const Text('4-6'), ], ), ], ), ), ); // #enddocregion iconList // #docregion leftColumn final leftColumn = Container( padding: const EdgeInsets.fromLTRB(20, 30, 20, 20), child: Column( children: [ titleText, subTitle, ratings, iconList, ], ), ); // #enddocregion leftColumn final mainImage = Image.asset( 'images/pavlova.jpg', fit: BoxFit.cover, ); return Scaffold( appBar: AppBar( title: Text(title), ), // #docregion body body: Center( child: Container( margin: const EdgeInsets.fromLTRB(0, 40, 0, 30), height: 600, child: Card( child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: 440, child: leftColumn, ), mainImage, ], ), ), ), ), // #enddocregion body ); } }
website/examples/layout/pavlova/lib/main.dart/0
{ "file_path": "website/examples/layout/pavlova/lib/main.dart", "repo_id": "website", "token_count": 2189 }
1,277
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show debugPaintSizeEnabled; void main() { debugPaintSizeEnabled = true; // Remove to suppress visual layout runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter layout demo', home: Scaffold( appBar: AppBar( title: const Text('Flutter layout demo'), ), // Change to buildFoo() for the other examples body: Center(child: buildExpandedImages()), ), ); } Widget buildOverflowingRow() => // #docregion overflowing-row Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); // #enddocregion overflowing-row Widget buildExpandedImages() => // #docregion expanded-images Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Image.asset('images/pic1.jpg'), ), Expanded( child: Image.asset('images/pic2.jpg'), ), Expanded( child: Image.asset('images/pic3.jpg'), ), ], ); // #enddocregion expanded-images Widget buildExpandedImagesWithFlex() => // #docregion expanded-images-with-flex Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Image.asset('images/pic1.jpg'), ), Expanded( flex: 2, child: Image.asset('images/pic2.jpg'), ), Expanded( child: Image.asset('images/pic3.jpg'), ), ], ); // #enddocregion expanded-images-with-flex }
website/examples/layout/sizing/lib/main.dart/0
{ "file_path": "website/examples/layout/sizing/lib/main.dart", "repo_id": "website", "token_count": 902 }
1,278
import 'dart:developer'; void someFunction(double offset) { debugger(when: offset > 30); // ... }
website/examples/testing/code_debugging/lib/debugger.dart/0
{ "file_path": "website/examples/testing/code_debugging/lib/debugger.dart", "repo_id": "website", "token_count": 35 }
1,279
name: assets_and_images description: An example project showing how to declare and load assets. publish_to: none environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.6 dev_dependencies: example_utils: path: ../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true assets: - assets/my_icon.png - assets/background.png
website/examples/ui/assets_and_images/pubspec.yaml/0
{ "file_path": "website/examples/ui/assets_and_images/pubspec.yaml", "repo_id": "website", "token_count": 165 }
1,280
import 'dart:io' show Platform; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; Widget layoutBuilderWidget() { // #docregion LayoutBuilder Widget foo = LayoutBuilder(builder: (context, constraints) { bool useVerticalLayout = constraints.maxWidth < 400; return Flex( direction: useVerticalLayout ? Axis.vertical : Axis.horizontal, children: const [ Text('Hello'), Text('World'), ], ); }); // #enddocregion LayoutBuilder return foo; } class ScrollListen extends StatelessWidget { const ScrollListen({super.key}); Widget scrollListener(BuildContext context) { // #docregion PointerScroll return Listener( onPointerSignal: (event) { if (event is PointerScrollEvent) print(event.scrollDelta.dy); }, child: ListView(), ); // #enddocregion PointerScroll } @override Widget build(BuildContext context) { // TODO: implement build throw UnimplementedError(); } } // #docregion Shortcuts // Define a class for each type of shortcut action you want class CreateNewItemIntent extends Intent { const CreateNewItemIntent(); } Widget build(BuildContext context) { return Shortcuts( // Bind intents to key combinations shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyN, control: true): CreateNewItemIntent(), }, child: Actions( // Bind intents to an actual method in your code actions: <Type, Action<Intent>>{ CreateNewItemIntent: CallbackAction<CreateNewItemIntent>( onInvoke: (intent) => _createNewItem(), ), }, // Your sub-tree must be wrapped in a focusNode, so it can take focus. child: Focus( autofocus: true, child: Container(), ), ), ); } // #enddocregion Shortcuts void _createNewItem() { // ignore: unnecessary_statements DoNothingAction; } class MyWidget extends StatefulWidget { const MyWidget({super.key, required this.title}); final String title; @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { // #docregion MultiSelectShift static bool get isSpanSelectModifierDown => isKeyDown({LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight}); // #enddocregion MultiSelectShift // #docregion MultiSelectModifierDown static bool get isMultiSelectModifierDown { bool isDown = false; if (Platform.isMacOS) { isDown = isKeyDown( {LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight}, ); } else { isDown = isKeyDown( {LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlRight}, ); } return isDown; } // #enddocregion MultiSelectModifierDown // #docregion HandleKey bool _handleKey(KeyEvent event) { bool isShiftDown = isKeyDown({ LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight, }); if (isShiftDown && event.logicalKey == LogicalKeyboardKey.keyN) { _createNewItem(); return true; } return false; } // #enddocregion HandleKey // #docregion KeysPressed static bool isKeyDown(Set<LogicalKeyboardKey> keys) { return keys .intersection(HardwareKeyboard.instance.logicalKeysPressed) .isNotEmpty; } // #enddocregion KeysPressed // #docregion hardware-keyboard @override void initState() { super.initState(); HardwareKeyboard.instance.addHandler(_handleKey); } @override void dispose() { HardwareKeyboard.instance.removeHandler(_handleKey); super.dispose(); } // #enddocregion hardware-keyboard @override Widget build(BuildContext context) { isSpanSelectModifierDown; isMultiSelectModifierDown; return const Text('Hello World!'); } } Widget selectableTextWidget() { // #docregion SelectableText return const SelectableText('Select me!'); // #enddocregion SelectableText } Widget richTextSpan() { // #docregion RichTextSpan return const SelectableText.rich( TextSpan( children: [ TextSpan(text: 'Hello'), TextSpan(text: 'Bold', style: TextStyle(fontWeight: FontWeight.bold)), ], ), ); // #enddocregion RichTextSpan } Widget tooltipWidget() { // #docregion Tooltip return const Tooltip( message: 'I am a Tooltip', child: Text('Hover over the text to show a tooltip.'), ); // #enddocregion Tooltip }
website/examples/ui/layout/adaptive_app_demos/lib/widgets/extra_widget_excerpts.dart/0
{ "file_path": "website/examples/ui/layout/adaptive_app_demos/lib/widgets/extra_widget_excerpts.dart", "repo_id": "website", "token_count": 1630 }
1,281
import 'package:flutter/rendering.dart'; void showLayoutGuidelines() { debugPaintSizeEnabled = true; }
website/examples/visual_debugging/lib/layout_guidelines.dart/0
{ "file_path": "website/examples/visual_debugging/lib/layout_guidelines.dart", "repo_id": "website", "token_count": 35 }
1,282
- group: 'China Flutter User Group' mirror: 'flutter-io.cn' urls: pubhosted: 'https://pub.flutter-io.cn' flutterstorage: 'https://storage.flutter-io.cn' issues: 'https://github.com/cfug/flutter.cn/issues/new/choose' group: https://github.com/cfug - group: 'Shanghai Jiao Tong University *nix User Group' mirror: 'mirror.sjtu.edu.cn' urls: pubhosted: 'https://mirror.sjtu.edu.cn/dart-pub' flutterstorage: 'https://mirror.sjtu.edu.cn' issues: 'https://github.com/sjtug/mirror-requests' group: https://github.com/sjtug - group: 'Tsinghua University TUNA Association' mirror: 'mirrors.tuna.tsinghua.edu.cn' urls: pubhosted: 'https://mirrors.tuna.tsinghua.edu.cn/dart-pub' flutterstorage: 'https://mirrors.tuna.tsinghua.edu.cn/flutter' issues: 'https://github.com/tuna/issues' group: https://tuna.moe
website/src/_data/mirrors.yml/0
{ "file_path": "website/src/_data/mirrors.yml", "repo_id": "website", "token_count": 365 }
1,283
{% assign path_base = page.url %} {% assign dirs = include.pages | where_exp: "item", "item.url contains path_base" | where_exp: "item", "item.url != path_base" | group_by_exp: "item", "item.url | remove: path_base | split: '/' | first" | sort: "name" %} {% for dir in dirs %} {% assign dir_name = dir.name | capitalize %} <h2 id="{{dir.name}}">{{ dir_name }}</h2> {% assign items = dir.items | where_exp: "item", "item.title != dir_name" | sort: "title" %} {% for item in items %} - [{{ item.title }}]({{ item.url }}) {% endfor %} {% endfor %}
website/src/_includes/docs/cookbook-toc.md/0
{ "file_path": "website/src/_includes/docs/cookbook-toc.md", "repo_id": "website", "token_count": 252 }
1,284
<details markdown="1"> <summary><b>How to install Chrome from the command line</b></summary> ```terminal $ wget https://dl-ssl.google.com/linux/linux_signing_key.pub -O /tmp/google.pub $ gpg --no-default-keyring \ --keyring /etc/apt/keyrings/google-chrome.gpg \ --import /tmp/google.pub $ echo 'deb [arch=amd64 signed-by=/etc/apt/keyrings/google-chrome.gpg] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list $ sudo apt-get update -y; sudo apt-get install -y google-chrome-stable ``` </details>
website/src/_includes/docs/install/accordions/install-chrome-from-cli.md/0
{ "file_path": "website/src/_includes/docs/install/accordions/install-chrome-from-cli.md", "repo_id": "website", "token_count": 217 }
1,285
When you run the current version of `flutter doctor`, it might list a different version of one of these packages. If it does, install the version it recommends.
website/src/_includes/docs/install/reqs/flutter-sdk/flutter-doctor-precedence.md/0
{ "file_path": "website/src/_includes/docs/install/reqs/flutter-sdk/flutter-doctor-precedence.md", "repo_id": "website", "token_count": 37 }
1,286
{% assign terminal=include.terminal %} ### Update your Windows PATH variable {:.no_toc} {% include docs/help-link.md location='win-path' section='#unable-to-find-the-flutter-command' %} To run Flutter commands in {{terminal}}, add Flutter to the `PATH` environment variable. This section presumes that you installed the Flutter SDK in `%USERPROFILE%\dev\flutter`. {% include docs/install/reqs/windows/open-envvars.md %} 1. In the **User variables for (username)** section, look for the **Path** entry. {:type="a"} 1. If the entry exists, double-click on it. The **Edit Environment Variable** dialog displays. {:type="i"} 1. Double-click in an empty row. 1. Type `%USERPROFILE%\dev\flutter\bin`. 1. Click the **%USERPROFILE%\dev\flutter\bin** entry. 1. Click **Move Up** until the Flutter entry sits at the top of the list. 1. Click **OK** three times. 1. If the entry doesn't exist, click **New...**. The **Edit Environment Variable** dialog displays. {:type="i"} 1. In the **Variable Name** box, type `Path`. 1. In the **Variable Value** box, type `%USERPROFILE%\dev\flutter\bin` 1. Click **OK** three times. 1. To enable these changes, close and reopen any existing command prompts and {{terminal}} instances.
website/src/_includes/docs/install/reqs/windows/set-path.md/0
{ "file_path": "website/src/_includes/docs/install/reqs/windows/set-path.md", "repo_id": "website", "token_count": 467 }
1,287
<footer class="site-footer"> <div class="container-fluid"> <div class="row"> <div class="col-md-12 site-footer__wrapper"> <div class="site-footer__logo"> <img src="/assets/images/branding/flutter/logo/flutter-mono-81x100.png" alt="Flutter Logo" width="81" height="100"> </div> <div class="site-footer__content"> <ul class="site-footer__link-list"> <li><a href="/tos">terms</a></li> <li><a href="/brand">brand usage</a></li> <li><a href="/security">security</a></li> <li><a href="https://www.google.com/intl/en/policies/privacy">privacy</a></li> <li><a href="https://esflutter.dev/">español</a></li> <li><a href="https://flutter.cn" class="text-nowrap">社区中文资源</a></li> <li><a href="https://blog.google/inside-google/company-announcements/standing-with-black-community">We stand in solidarity with the Black community. Black Lives Matter.</a></li> </ul> <p class="licenses"> Except as otherwise noted, this work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by/4.0">Creative Commons Attribution 4.0 International License</a>, and code samples are licensed under the BSD License. </p> </div> </div> </div> </div> </footer>
website/src/_includes/footer.html/0
{ "file_path": "website/src/_includes/footer.html", "repo_id": "website", "token_count": 666 }
1,288
--- layout: base --- <div class="container"> <div class="row"> <main class="col-12"> {{content}} </main> </div> </div>
website/src/_layouts/landing.html/0
{ "file_path": "website/src/_layouts/landing.html", "repo_id": "website", "token_count": 61 }
1,289
require 'cgi' require_relative 'dart_site_util' module DartSite # Base class used by some Liquid Block plugins to render code that gets # prettified by https://github.com/google/code-prettify. # # The following markup syntax can be used to apply a CSS class to a span # of code: # # `[[foo]]some code[[/foo]]` # # will render as # # `<span class="foo">some code</span>` # # Note that `[[highlight]]...[[/highlight]]` can be abbreviated using the # following shorthand: `[!...!]`. # class PrettifyCore # @param code [String], raw code to be converted to HTML. # @param lang [String], e.g., 'dart', 'json' or 'yaml' # @param tag_specifier [String] matching "pre|pre+code|code|code+br". # This is the HTML element used to wrap the prettified # code. The `code` element is used for `code+br`; in addition, # newlines in the code excerpt are reformatted at `<br>` elements. # @param user_classes [String] zero or more space separated CSS class names # to be applied to the outter-most enclosing tag. # @param context [String] 'html' or 'markdown' (default), represents whether # the tag is being rendered in an HTML or a markdown document. Indentation # is preserved for markdown but not for HTML. def code2html(code, lang: nil, context: 'markdown', tag_specifier: 'pre', user_classes: nil) tag = _get_real_tag(tag_specifier || 'pre') css_classes = _css_classes(lang, user_classes) class_attr = css_classes.empty? ? '' : " class=\"#{css_classes.join(' ')}\"" out = "<#{tag}#{class_attr}>" out += '<code>' if tag_specifier == 'pre+code' code = context == 'markdown' ? Util.block_trim_leading_whitespace(code.split(/\n/)).join("\n") : Util.trim_min_leading_space(code) # Strip leading and trailing whitespace so that <pre> and </pre> tags wrap tightly code.strip! code = CGI.escapeHTML(code) if tag_specifier == 'code+br' code.gsub!(/\n[ \t]*/) { |s| "<br>\n#{'&nbsp;' * (s.length - 1)}" } end # Names of tags previously supported: highlight, note, red, strike. code.gsub!(/\[\[([\w-]+)\]\]/, '<span class="\1">') code.gsub!(/\[\[\/([\w-]*)\]\]/, '</span>') # Flutter tag syntax variant: code.gsub!(/\/\*\*([\w-]+)\*\//, '<span class="\1">') code.gsub!(/\/\*-([\w-]*)\*\//, '</span>') code.gsub!('[!', '<span class="highlight">') code.gsub!('!]', '</span>') out += code out += '</code>' if tag_specifier == 'pre+code' out += "</#{tag}>" end private def _css_classes(lang, user_classes) css_classes = [] unless lang == 'nocode' || lang == 'none' css_classes << 'prettyprint' css_classes << "lang-#{lang}" if lang end css_classes << user_classes if user_classes css_classes end # Returns the word before the '+' if tag_specifier contains a '+', # tag_specifier otherwise def _get_real_tag(tag_specifier) tag_specifier[/^[^\+]+(?=\+)/] || tag_specifier end end end
website/src/_plugins/prettify_core.rb/0
{ "file_path": "website/src/_plugins/prettify_core.rb", "repo_id": "website", "token_count": 1314 }
1,290
// A big button centered on top of an image. // // The container is typically a <div> element. The div has only 2 children: // an <img> element (the background) and a <a class="btn"> button. // // The image should be very bright and slightly blurred so that the button // stands out. .juicy-button-container { position: relative; width: 100%; padding: 2em 0; img { // Take available space in the container. width: 100%; height: auto; } .btn { // Center the button in the container. position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); // Add a white "glow" that separates the button from the background. box-shadow: 0 0 10px 10px white ; // Make the button extra large. @media (min-width: 600px) { font-size: 150%; padding: 0.7rem; } @media (min-width: 900px) { font-size: 200%; padding: 1.0rem; } } }
website/src/_sass/components/_juicy-button.scss/0
{ "file_path": "website/src/_sass/components/_juicy-button.scss", "repo_id": "website", "token_count": 352 }
1,291
--- title: Integrate a Flutter module into your Android project short-title: Integrate Flutter description: Learn how to integrate a Flutter module into your existing Android project. --- Flutter can be embedded into your existing Android application piecemeal, as a source code Gradle subproject or as AARs. The integration flow can be done using the Android Studio IDE with the [Flutter plugin][] or manually. {{site.alert.warning}} Your existing Android app might support architectures such as `mips` or `x86`. Flutter currently [only supports][] building ahead-of-time (AOT) compiled libraries for `x86_64`, `armeabi-v7a`, and `arm64-v8a`. Consider using the [`abiFilters`][] Android Gradle Plugin API to limit the supported architectures in your APK. Doing this avoids a missing `libflutter.so` runtime crash, for example: <?code-excerpt title="MyApp/app/build.gradle"?> ```gradle android { //... defaultConfig { ndk { // Filter for architectures supported by Flutter. abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64' } } } ``` The Flutter engine has an `x86` and `x86_64` version. When using an emulator in debug Just-In-Time (JIT) mode, the Flutter module still runs correctly. {{site.alert.end}} ## Integrate your Flutter module {% comment %} Nav tabs {% endcomment -%} <ul class="nav nav-tabs" id="add-to-app-android" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="with-android-studio-tab" href="#with-android-studio" role="tab" aria-controls="with-android-studio" aria-selected="true">With Android Studio</a> </li> <li class="nav-item"> <a class="nav-link" id="without-android-studio-tab" href="#without-android-studio" role="tab" aria-controls="without-android-studio" aria-selected="false">Without Android Studio</a> </li> </ul> {% comment %} Tab panes {% endcomment -%} <div class="tab-content"> <div class="tab-pane active" id="with-android-studio" role="tabpanel" aria-labelledby="with-android-studio-tab" markdown="1"> ### Integrate with Android Studio {:.no_toc} The Android Studio IDE can help integrate your Flutter module. Using Android Studio, you can edit both your Android and Flutter code in the same IDE. You can also use IntelliJ Flutter plugin functionality like Dart code completion, hot reload, and widget inspector. Android Studio supports add-to-app flows on Android Studio 2022.2 or later with the [Flutter plugin][] for IntelliJ. To build your app, the Android Studio plugin configures your Android project to add your Flutter module as a dependency. 1. Open your Android project in Android Studio. 1. Go to **File** > **New** > **New Project...**. The **New Project** dialog displays. 1. Click **Flutter**. 1. If asked to provide your **Flutter SDK path**, do so and click **Next**. 1. Complete the configuration of your Flutter module. * If you have an existing project: {: type="a"} 1. To choose an existing project, click **...** to the right of the **Project location** box. 1. Navigate to your Flutter project directory. 1. Click **Open**. * If you need to create a new Flutter project: {: type="a"} 1. Complete the configuration dialog. 1. In the **Project type** menu, select **Module**. 1. Click **Finish**. {{site.alert.tip}} By default, your project's Project pane might show the 'Android' view. If you can't see your new Flutter files in the Project pane, set your Project pane to display **Project Files**. This shows all files without filtering. {{site.alert.end}} </div> <div class="tab-pane" id="without-android-studio" role="tabpanel" aria-labelledby="without-android-studio-tab" markdown="1"> ### Integrate without Android Studio {:.no_toc} To integrate a Flutter module with an existing Android app manually, without using Flutter's Android Studio plugin, follow these steps: #### Create a Flutter module Let's assume that you have an existing Android app at `some/path/MyApp`, and that you want your Flutter project as a sibling: ```terminal cd some/path/ flutter create -t module --org com.example flutter_module ``` This creates a `some/path/flutter_module/` Flutter module project with some Dart code to get you started and an `.android/` hidden subfolder. The `.android` folder contains an Android project that can both help you run a barebones standalone version of your Flutter module via `flutter run` and it's also a wrapper that helps bootstrap the Flutter module an embeddable Android library. {{site.alert.note}} Add custom Android code to your own existing application's project or a plugin, not to the module in `.android/`. Changes made in your module's `.android/` directory won't appear in your existing Android project using the module. Do not source control the `.android/` directory since it's autogenerated. Before building the module on a new machine, run `flutter pub get` in the `flutter_module` directory first to regenerate the `.android/` directory before building the Android project using the Flutter module. {{site.alert.end}} {{site.alert.note}} To avoid Dex merging issues, `flutter.androidPackage` should not be identical to your host app's package name. {{site.alert.end}} #### Java version requirement Flutter requires your project to declare compatibility with Java 11 or later. Before attempting to connect your Flutter module project to your host Android app, ensure that your host Android app declares the following source compatibility within your app's `build.gradle` file, under the `android { }` block. <?code-excerpt title="MyApp/app/build.gradle"?> ```gradle android { //... compileOptions { sourceCompatibility 11 // The minimum value targetCompatibility 11 // The minimum value } } ``` #### Centralize repository settings Starting with Gradle 7, Android recommends using centralized repository declarations in `settings.gradle` instead of project or module level declarations in `build.gradle` files. Before attempting to connect your Flutter module project to your host Android app, make the following changes. 1. Remove the `repositories` block in all of your app's `build.gradle` files. ```groovy // Remove the following block, starting on the next line repositories { google() mavenCentral() } // ...to the previous line ``` 1. Add the `dependencyResolutionManagement` displayed in this step to the `settings.gradle` file. ```groovy dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) repositories { google() mavenCentral() } } ``` </div> </div> {% comment %} End: Tab panes. {% endcomment -%} ## Add the Flutter module as a dependency Add the Flutter module as a dependency of your existing app in Gradle. You can achieve this in two ways. 1. **Android archive** The AAR mechanism creates generic Android AARs as intermediaries that packages your Flutter module. This is good when your downstream app builders don't want to have the Flutter SDK installed. But, it adds one more build step if you build frequently. 1. **Module source code** The source code subproject mechanism is a convenient one-click build process, but requires the Flutter SDK. This is the mechanism used by the Android Studio IDE plugin. {% comment %} Nav tabs {% endcomment -%} <ul class="nav nav-tabs" id="add-to-app-android-deps" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="android-archive-tab" href="#android-archive" role="tab" aria-controls="android-archive" aria-selected="true">Android Archive</a> </li> <li class="nav-item"> <a class="nav-link" id="module-source-tab" href="#module-source" role="tab" aria-controls="module-source" aria-selected="false">Module source code</a> </li> </ul> {% comment %} Tab panes {% endcomment -%} <div class="tab-content"> <div class="tab-pane active" id="android-archive" role="tabpanel" aria-labelledby="android-archive-tab" markdown="1"> ### Depend on the Android Archive (AAR) {:.no_toc} This option packages your Flutter library as a generic local Maven repository composed of AARs and POMs artifacts. This option allows your team to build the host app without installing the Flutter SDK. You can then distribute the artifacts from a local or remote repository. Let's assume you built a Flutter module at `some/path/flutter_module`, and then run: ```terminal cd some/path/flutter_module flutter build aar ``` Then, follow the on-screen instructions to integrate. {% include docs/app-figure.md image="development/add-to-app/android/project-setup/build-aar-instructions.png" %} More specifically, this command creates (by default all debug/profile/release modes) a [local repository][], with the following files: ```nocode build/host/outputs/repo └── com └── example └── flutter_module ├── flutter_release │ ├── 1.0 │ │   ├── flutter_release-1.0.aar │ │   ├── flutter_release-1.0.aar.md5 │ │   ├── flutter_release-1.0.aar.sha1 │ │   ├── flutter_release-1.0.pom │ │   ├── flutter_release-1.0.pom.md5 │ │   └── flutter_release-1.0.pom.sha1 │ ├── maven-metadata.xml │ ├── maven-metadata.xml.md5 │ └── maven-metadata.xml.sha1 ├── flutter_profile │ ├── ... └── flutter_debug └── ... ``` To depend on the AAR, the host app must be able to find these files. To do that, edit `settings.gradle` in your host app so that it includes the local repository and the dependency: ```gradle dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) repositories { google() mavenCentral() // Add the new repositories starting on the next line... maven { url 'some/path/flutter_module/build/host/outputs/repo' // This is relative to the location of the build.gradle file // if using a relative path. } maven { url 'https://storage.googleapis.com/download.flutter.io' } // ...to before this line } } ``` </br> ### Kotlin DSL based Android Project After an `aar` build of a Kotlin DSL-based Android project, follow these steps to add the flutter_module. Include the flutter module as a dependency in the Android project's `app/build.gradle` file. <?code-excerpt title="MyApp/app/build.gradle.kts"?> ```gradle android { buildTypes { release { ... } debug { ... } create("profile") { initWith(getByName("debug")) } } dependencies { // ... debugImplementation "com.example.flutter_module:flutter_debug:1.0" releaseImplementation 'com.example.flutter_module:flutter_release:1.0' add("profileImplementation", "com.example.flutter_module:flutter_profile:1.0") } ``` The `profileImplementation` ID is a custom `configuration` to be implemented in the `app/build.gradle` file of a host project. <?code-excerpt title="host-project/app/build.gradle.kts"?> ```gradle configurations { getByName("profileImplementation") { } } ``` <?code-excerpt title="MyApp/settings.gradle.kts"?> ```gradle include(":app") dependencyResolutionManagement { repositories { maven(url = "https://storage.googleapis.com/download.flutter.io") maven(url = "some/path/flutter_module_project/build/host/outputs/repo") } } ``` {{site.alert.important}} If you're located in China, use a mirror site rather than the `storage.googleapis.com` domain. To learn more about mirror sites, check out [Using Flutter in China][] page. {{site.alert.end}} {{site.alert.tip}} You can also build an AAR for your Flutter module in Android Studio using the `Build > Flutter > Build AAR` menu. {% include docs/app-figure.md image="development/add-to-app/android/project-setup/ide-build-aar.png" %} {{site.alert.end}} </div> <div class="tab-pane" id="module-source" role="tabpanel" aria-labelledby="module-source-tab" markdown="1"> ### Depend on the module's source code {:.no_toc} This option enables a one-step build for both your Android project and Flutter project. This option is convenient when you work on both parts simultaneously and rapidly iterate, but your team must install the Flutter SDK to build the host app. {{site.alert.tip}} By default, the host app provides the `:app` Gradle project. To change the name of this project, set `flutter.hostAppProjectName` in the Flutter module's `gradle.properties` file. Include this project in the host app's `settings.gradle` file. {{site.alert.end}} Include the Flutter module as a subproject in the host app's `settings.gradle`. This example assumes `flutter_module` and `MyApp` exist in the same directory <?code-excerpt title="MyApp/settings.gradle"?> ```groovy // Include the host app project. include ':app' // assumed existing content setBinding(new Binding([gradle: this])) // new evaluate(new File( // new settingsDir.parentFile, // new 'flutter_module/.android/include_flutter.groovy' // new )) // new ``` The binding and script evaluation allows the Flutter module to `include` itself (as `:flutter`) and any Flutter plugins used by the module (such as `:package_info` and `:video_player`) in the evaluation context of your `settings.gradle`. Introduce an `implementation` dependency on the Flutter module from your app: <?code-excerpt title="MyApp/app/build.gradle"?> ```groovy dependencies { implementation project(':flutter') } ``` </div> </div> {% comment %} End: Tab panes. {% endcomment -%} Your app now includes the Flutter module as a dependency. Continue to the [Adding a Flutter screen to an Android app][] guide. [`abiFilters`]: {{site.android-dev}}/reference/tools/gradle-api/4.2/com/android/build/api/dsl/Ndk#abiFilters:kotlin.collections.MutableSet [Adding a Flutter screen to an Android app]: /add-to-app/android/add-flutter-screen [Flutter plugin]: https://plugins.jetbrains.com/plugin/9212-flutter [local repository]: https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:maven_local [only supports]: /resources/faq#what-devices-and-os-versions-does-flutter-run-on [Using Flutter in China]: /community/china
website/src/add-to-app/android/project-setup.md/0
{ "file_path": "website/src/add-to-app/android/project-setup.md", "repo_id": "website", "token_count": 5079 }
1,292
The owl.jpeg image is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license. It was originally created by Trebol-a and has been modified for this site. https://creativecommons.org/licenses/by-sa/3.0/deed.en https://commons.wikimedia.org/wiki/User:Trebol-a https://commons.wikimedia.org/wiki/File:Athene_noctua_(portrait).jpg
website/src/assets/images/docs/LICENSE/0
{ "file_path": "website/src/assets/images/docs/LICENSE", "repo_id": "website", "token_count": 116 }
1,293
{% assign id = include.ref-os | downcase -%} {% assign mainpath = include.filepath -%} {%- case id %} {% when 'windows','macos' %} {%- assign file-format = 'zip' %} {% else %} {%- assign file-format = 'tar.xz' %} {% endcase %} {%- if id == 'chromeos' %} {% assign plat = 'linux' %} {%- else %} {% assign plat = id %} {% endif %} {% capture filepath -%}{{mainpath | replace: "opsys", plat}}{{file-format}} {% endcapture -%} <div id="{{id}}-dl" class="tab-pane {%- if id == 'windows' %} active {% endif %}" role="tabpanel" aria-labelledby="{{id}}-dl-tab" markdown="1"> To download the {{include.ref-os}} 3.13 version of the Flutter SDK, you would change the original URL from: ```terminal https://storage.googleapis.com/{{filepath}} ``` to the mirror URL: ```terminal https://storage.flutter-io.cn/{{filepath}} ``` </div>
website/src/community/china/_download-urls.md/0
{ "file_path": "website/src/community/china/_download-urls.md", "repo_id": "website", "token_count": 326 }
1,294
--- title: Use themes to share colors and font styles short-title: Themes description: How to share colors and font styles throughout an app using Themes. js: - defer: true url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js --- <?code-excerpt path-base="cookbook/design/themes"?> {{site.alert.note}} This recipe uses Flutter's support for [Material 3][] and the [google_fonts][] package. As of the Flutter 3.16 release, Material 3 is Flutter's default theme. {{site.alert.end}} [Material 3]: /ui/design/material [google_fonts]: {{site.pub-pkg}}/google_fonts To share colors and font styles throughout an app, use themes. You can define app-wide themes. You can extend a theme to change a theme style for one component. Each theme defines the colors, type style, and other parameters applicable for the type of Material component. Flutter applies styling in the following order: 1. Styles applied to the specific widget. 1. Themes that override the immediate parent theme. 1. Main theme for the entire app. After you define a `Theme`, use it within your own widgets. Flutter's Material widgets use your theme to set the background colors and font styles for app bars, buttons, checkboxes, and more. ## Create an app theme To share a `Theme` across your entire app, set the `theme` property to your `MaterialApp` constructor. This property takes a [`ThemeData`][] instance. As of the Flutter 3.16 release, Material 3 is Flutter's default theme. If you don't specify a theme in the constructor, Flutter creates a default theme for you. <?code-excerpt "lib/main.dart (MaterialApp)" replace="/return //g"?> ```dart MaterialApp( title: appName, theme: ThemeData( useMaterial3: true, // Define the default brightness and colors. colorScheme: ColorScheme.fromSeed( seedColor: Colors.purple, // ··· brightness: Brightness.dark, ), // Define the default `TextTheme`. Use this to specify the default // text styling for headlines, titles, bodies of text, and more. textTheme: TextTheme( displayLarge: const TextStyle( fontSize: 72, fontWeight: FontWeight.bold, ), // ··· titleLarge: GoogleFonts.oswald( fontSize: 30, fontStyle: FontStyle.italic, ), bodyMedium: GoogleFonts.merriweather(), displaySmall: GoogleFonts.pacifico(), ), ), home: const MyHomePage( title: appName, ), ); ``` Most instances of `ThemeData` set values for the following two properties. These properties affect the entire app. 1. [`colorScheme`][] defines the colors. 1. [`textTheme`][] defines text styling. [`colorScheme`]: {{site.api}}/flutter/material/ThemeData/colorScheme.html [`textTheme`]: {{site.api}}/flutter/material/ThemeData/textTheme.html To learn what colors, fonts, and other properties, you can define, check out the [`ThemeData`][] documentation. ## Apply a theme To apply your new theme, use the `Theme.of(context)` method when specifying a widget's styling properties. These can include, but are not limited to, `style` and `color`. The `Theme.of(context)` method looks up the widget tree and retrieves the nearest `Theme` in the tree. If you have a standalone `Theme`, that's applied. If not, Flutter applies the app's theme. In the following example, the `Container` constructor uses this technique to set its `color`. <?code-excerpt "lib/main.dart (Container)" replace="/^child: //g"?> ```dart Container( padding: const EdgeInsets.symmetric( horizontal: 12, vertical: 12, ), color: Theme.of(context).colorScheme.primary, child: Text( 'Text with a background color', // ··· style: Theme.of(context).textTheme.bodyMedium!.copyWith( color: Theme.of(context).colorScheme.onPrimary, ), ), ), ``` ## Override a theme To override the overall theme in part of an app, wrap that section of the app in a `Theme` widget. You can override a theme in two ways: 1. Create a unique `ThemeData` instance. 2. Extend the parent theme. ### Set a unique `ThemeData` instance If you want a component of your app to ignore the overall theme, create a `ThemeData` instance. Pass that instance to the `Theme` widget. <?code-excerpt "lib/main.dart (Theme)"?> ```dart Theme( // Create a unique theme with `ThemeData`. data: ThemeData( colorScheme: ColorScheme.fromSeed( seedColor: Colors.pink, ), ), child: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.add), ), ); ``` ### Extend the parent theme Instead of overriding everything, consider extending the parent theme. To extend a theme, use the [`copyWith()`][] method. <?code-excerpt "lib/main.dart (ThemeCopyWith)"?> ```dart Theme( // Find and extend the parent theme using `copyWith`. // To learn more, check out the section on `Theme.of`. data: Theme.of(context).copyWith( colorScheme: ColorScheme.fromSeed( seedColor: Colors.pink, ), ), child: const FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), ); ``` ## Watch a video on `Theme` To learn more, watch this short Widget of the Week video on the `Theme` widget: <iframe class="full-width" src="{{site.yt.embed}}/oTvQDJOBXmM" title="Learn about the Theme Flutter Widget" {{site.yt.set}}></iframe> ## Try an interactive example <?code-excerpt "lib/main.dart (FullApp)"?> ```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example import 'package:flutter/material.dart'; // Include the Google Fonts package to provide more text format options // https://pub.dev/packages/google_fonts import 'package:google_fonts/google_fonts.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appName = 'Custom Themes'; return MaterialApp( title: appName, theme: ThemeData( useMaterial3: true, // Define the default brightness and colors. colorScheme: ColorScheme.fromSeed( seedColor: Colors.purple, // TRY THIS: Change to "Brightness.light" // and see that all colors change // to better contrast a light background. brightness: Brightness.dark, ), // Define the default `TextTheme`. Use this to specify the default // text styling for headlines, titles, bodies of text, and more. textTheme: TextTheme( displayLarge: const TextStyle( fontSize: 72, fontWeight: FontWeight.bold, ), // TRY THIS: Change one of the GoogleFonts // to "lato", "poppins", or "lora". // The title uses "titleLarge" // and the middle text uses "bodyMedium". titleLarge: GoogleFonts.oswald( fontSize: 30, fontStyle: FontStyle.italic, ), bodyMedium: GoogleFonts.merriweather(), displaySmall: GoogleFonts.pacifico(), ), ), home: const MyHomePage( title: appName, ), ); } } class MyHomePage extends StatelessWidget { final String title; const MyHomePage({super.key, required this.title}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title, style: Theme.of(context).textTheme.titleLarge!.copyWith( color: Theme.of(context).colorScheme.onSecondary, )), backgroundColor: Theme.of(context).colorScheme.secondary, ), body: Center( child: Container( padding: const EdgeInsets.symmetric( horizontal: 12, vertical: 12, ), color: Theme.of(context).colorScheme.primary, child: Text( 'Text with a background color', // TRY THIS: Change the Text value // or change the Theme.of(context).textTheme // to "displayLarge" or "displaySmall". style: Theme.of(context).textTheme.bodyMedium!.copyWith( color: Theme.of(context).colorScheme.onPrimary, ), ), ), ), floatingActionButton: Theme( data: Theme.of(context).copyWith( // TRY THIS: Change the seedColor to "Colors.red" or // "Colors.blue". colorScheme: ColorScheme.fromSeed( seedColor: Colors.pink, brightness: Brightness.dark, ), ), child: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.add), ), ), ); } } ``` <noscript> <img src="/assets/images/docs/cookbook/themes.png" alt="Themes Demo" class="site-mobile-screenshot" /> </noscript> [`copyWith()`]: {{site.api}}/flutter/material/ThemeData/copyWith.html [`ThemeData`]: {{site.api}}/flutter/material/ThemeData-class.html
website/src/cookbook/design/themes.md/0
{ "file_path": "website/src/cookbook/design/themes.md", "repo_id": "website", "token_count": 3430 }
1,295
--- title: Create and style a text field description: How to implement a text field. js: - defer: true url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js --- <?code-excerpt path-base="cookbook/forms/text_input/"?> Text fields allow users to type text into an app. They are used to build forms, send messages, create search experiences, and more. In this recipe, explore how to create and style text fields. Flutter provides two text fields: [`TextField`][] and [`TextFormField`][]. ## `TextField` [`TextField`][] is the most commonly used text input widget. By default, a `TextField` is decorated with an underline. You can add a label, icon, inline hint text, and error text by supplying an [`InputDecoration`][] as the [`decoration`][] property of the `TextField`. To remove the decoration entirely (including the underline and the space reserved for the label), set the `decoration` to null. <?code-excerpt "lib/main.dart (TextField)" replace="/^child\: //g"?> ```dart TextField( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Enter a search term', ), ), ``` To retrieve the value when it changes, see the [Handle changes to a text field][] recipe. ## `TextFormField` [`TextFormField`][] wraps a `TextField` and integrates it with the enclosing [`Form`][]. This provides additional functionality, such as validation and integration with other [`FormField`][] widgets. <?code-excerpt "lib/main.dart (TextFormField)" replace="/^child\: //g"?> ```dart TextFormField( decoration: const InputDecoration( border: UnderlineInputBorder(), labelText: 'Enter your username', ), ), ``` ## Interactive example <?code-excerpt "lib/main.dart" replace="/^child\: //g"?> ```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Form Styling Demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: const Text(appTitle), ), body: const MyCustomForm(), ), ); } } class MyCustomForm extends StatelessWidget { const MyCustomForm({super.key}); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Padding( padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16), child: TextField( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Enter a search term', ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), child: TextFormField( decoration: const InputDecoration( border: UnderlineInputBorder(), labelText: 'Enter your username', ), ), ), ], ); } } ``` For more information on input validation, see the [Building a form with validation][] recipe. [Building a form with validation]: /cookbook/forms/validation/ [`decoration`]: {{site.api}}/flutter/material/TextField/decoration.html [`Form`]: {{site.api}}/flutter/widgets/Form-class.html [`FormField`]: {{site.api}}/flutter/widgets/FormField-class.html [Handle changes to a text field]: /cookbook/forms/text-field-changes/ [`InputDecoration`]: {{site.api}}/flutter/material/InputDecoration-class.html [`TextField`]: {{site.api}}/flutter/material/TextField-class.html [`TextFormField`]: {{site.api}}/flutter/material/TextFormField-class.html
website/src/cookbook/forms/text-input.md/0
{ "file_path": "website/src/cookbook/forms/text-input.md", "repo_id": "website", "token_count": 1379 }
1,296
--- title: Place a floating app bar above a list description: How to place a floating app bar above a list. js: - defer: true url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js --- <?code-excerpt path-base="cookbook/lists/floating_app_bar/"?> To make it easier for users to view a list of items, you might want to hide the app bar as the user scrolls down the list. This is especially true if your app displays a "tall" app bar that occupies a lot of vertical space. Typically, you create an app bar by providing an `appBar` property to the `Scaffold` widget. This creates a fixed app bar that always remains above the `body` of the `Scaffold`. Moving the app bar from a `Scaffold` widget into a [`CustomScrollView`][] allows you to create an app bar that scrolls offscreen as you scroll through a list of items contained inside the `CustomScrollView`. This recipe demonstrates how to use a `CustomScrollView` to display a list of items with an app bar on top that scrolls offscreen as the user scrolls down the list using the following steps: 1. Create a `CustomScrollView`. 2. Use `SliverAppBar` to add a floating app bar. 3. Add a list of items using a `SliverList`. ## 1. Create a `CustomScrollView` To create a floating app bar, place the app bar inside a `CustomScrollView` that also contains the list of items. This synchronizes the scroll position of the app bar and the list of items. You might think of the `CustomScrollView` widget as a `ListView` that allows you to mix and match different types of scrollable lists and widgets together. The scrollable lists and widgets provided to the `CustomScrollView` are known as _slivers_. There are several types of slivers, such as `SliverList`, `SliverGrid`, and `SliverAppBar`. In fact, the `ListView` and `GridView` widgets use the `SliverList` and `SliverGrid` widgets to implement scrolling. For this example, create a `CustomScrollView` that contains a `SliverAppBar` and a `SliverList`. In addition, remove any app bars that you provide to the `Scaffold` widget. <?code-excerpt "lib/starter.dart (CustomScrollView)" replace="/^return //g"?> ```dart Scaffold( // No appBar property provided, only the body. body: CustomScrollView( // Add the app bar and list of items as slivers in the next steps. slivers: <Widget>[]), ); ``` ### 2. Use `SliverAppBar` to add a floating app bar Next, add an app bar to the [`CustomScrollView`][]. Flutter provides the [`SliverAppBar`][] widget which, much like the normal `AppBar` widget, uses the `SliverAppBar` to display a title, tabs, images and more. However, the `SliverAppBar` also gives you the ability to create a "floating" app bar that scrolls offscreen as the user scrolls down the list. Furthermore, you can configure the `SliverAppBar` to shrink and expand as the user scrolls. To create this effect: 1. Start with an app bar that displays only a title. 2. Set the `floating` property to `true`. This allows users to quickly reveal the app bar when they scroll up the list. 3. Add a `flexibleSpace` widget that fills the available `expandedHeight`. <?code-excerpt "lib/step2.dart (SliverAppBar)" replace="/^body: //g;/,$//g"?> ```dart CustomScrollView( slivers: [ // Add the app bar to the CustomScrollView. const SliverAppBar( // Provide a standard title. title: Text(title), // Allows the user to reveal the app bar if they begin scrolling // back up the list of items. floating: true, // Display a placeholder widget to visualize the shrinking size. flexibleSpace: Placeholder(), // Make the initial height of the SliverAppBar larger than normal. expandedHeight: 200, ), ], ) ``` {{site.alert.tip}} Play around with the [various properties you can pass to the `SliverAppBar` widget][], and use hot reload to see the results. For example, use an `Image` widget for the `flexibleSpace` property to create a background image that shrinks in size as it's scrolled offscreen. {{site.alert.end}} ### 3. Add a list of items using a `SliverList` Now that you have the app bar in place, add a list of items to the `CustomScrollView`. You have two options: a [`SliverList`][] or a [`SliverGrid`][]. If you need to display a list of items one after the other, use the `SliverList` widget. If you need to display a grid list, use the `SliverGrid` widget. The `SliverList` and `SliverGrid` widgets take one required parameter: a [`SliverChildDelegate`][], which provides a list of widgets to `SliverList` or `SliverGrid`. For example, the [`SliverChildBuilderDelegate`][] allows you to create a list of items that are built lazily as you scroll, just like the `ListView.builder` widget. <?code-excerpt "lib/main.dart (SliverList)" replace="/,$//g"?> ```dart // Next, create a SliverList SliverList( // Use a delegate to build items as they're scrolled on screen. delegate: SliverChildBuilderDelegate( // The builder function returns a ListTile with a title that // displays the index of the current item. (context, index) => ListTile(title: Text('Item #$index')), // Builds 1000 ListTiles childCount: 1000, ), ) ``` ## Interactive example <?code-excerpt "lib/main.dart"?> ```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Floating App Bar'; return MaterialApp( title: title, home: Scaffold( // No appbar provided to the Scaffold, only a body with a // CustomScrollView. body: CustomScrollView( slivers: [ // Add the app bar to the CustomScrollView. const SliverAppBar( // Provide a standard title. title: Text(title), // Allows the user to reveal the app bar if they begin scrolling // back up the list of items. floating: true, // Display a placeholder widget to visualize the shrinking size. flexibleSpace: Placeholder(), // Make the initial height of the SliverAppBar larger than normal. expandedHeight: 200, ), // Next, create a SliverList SliverList( // Use a delegate to build items as they're scrolled on screen. delegate: SliverChildBuilderDelegate( // The builder function returns a ListTile with a title that // displays the index of the current item. (context, index) => ListTile(title: Text('Item #$index')), // Builds 1000 ListTiles childCount: 1000, ), ), ], ), ), ); } } ``` <noscript> <img src="/assets/images/docs/cookbook/floating-app-bar.gif" alt="Use list demo" class="site-mobile-screenshot"/> </noscript> [`CustomScrollView`]: {{site.api}}/flutter/widgets/CustomScrollView-class.html [`SliverAppBar`]: {{site.api}}/flutter/material/SliverAppBar-class.html [`SliverChildBuilderDelegate`]: {{site.api}}/flutter/widgets/SliverChildBuilderDelegate-class.html [`SliverChildDelegate`]: {{site.api}}/flutter/widgets/SliverChildDelegate-class.html [`SliverGrid`]: {{site.api}}/flutter/widgets/SliverGrid-class.html [`SliverList`]: {{site.api}}/flutter/widgets/SliverList-class.html [various properties you can pass to the `SliverAppBar` widget]: {{site.api}}/flutter/material/SliverAppBar/SliverAppBar.html
website/src/cookbook/lists/floating-app-bar.md/0
{ "file_path": "website/src/cookbook/lists/floating-app-bar.md", "repo_id": "website", "token_count": 2624 }
1,297
--- title: Set up app links for Android description: How set up universal links for an iOS application built with Flutter js: - defer: true url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js --- <?code-excerpt path-base="codelabs/deeplink_cookbook"?> Deep linking is a mechanism for launching an app with a URI. This URI contains scheme, host, and path, and opens the app to a specific screen. A _app link_ is a type of deep link that uses `http` or `https` and is exclusive to Android devices. Setting up app links requires one to own a web domain. Otherwise, consider using [Firebase Hosting][] or [GitHub Pages][] as a temporary solution. ## 1. Customize a Flutter application Write a Flutter app that can handle an incoming URL. This example uses the [go_router][] package to handle the routing. The Flutter team maintains the `go_router` package. It provides a simple API to handle complex routing scenarios. 1. To create a new application, type `flutter create <app-name>`: ```shell $ flutter create deeplink_cookbook ``` 2. To include `go_router` package in your app, add a dependency for `go_router` to the project: To add the `go_router` package as a dependency, run `flutter pub add`: ```terminal $ flutter pub add go_router ``` 3. To handle the routing, create a `GoRouter` object in the `main.dart` file: <?code-excerpt "lib/main.dart"?> ```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; void main() => runApp(MaterialApp.router(routerConfig: router)); /// This handles '/' and '/details'. final router = GoRouter( routes: [ GoRoute( path: '/', builder: (_, __) => Scaffold( appBar: AppBar(title: const Text('Home Screen')), ), routes: [ GoRoute( path: 'details', builder: (_, __) => Scaffold( appBar: AppBar(title: const Text('Details Screen')), ), ), ], ), ], ); ``` ## 2. Modify AndroidManifest.xml 1. Open the Flutter project with VS Code or Android Studio. 2. Navigate to `android/app/src/main/AndroidManifest.xml` file. 3. Add the following metadata tag and intent filter inside the `<activity>` tag with `.MainActivity`. Replace `example.com` with your own web domain. ``` <meta-data android:name="flutter_deeplinking_enabled" android:value="true" /> <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" android:host="example.com" /> <data android:scheme="https" /> </intent-filter> ``` {{site.alert.note}} The metadata tag flutter_deeplinking_enabled opts into Flutter's default deeplink handler. If you are using the third-party plugins, such as [uni_links][], setting this metadata tag will break these plugins. Omit this metadata tag if you prefer to use third-party plugins. {{site.alert.end}} ## 3. Hosting assetlinks.json file Host an `assetlinks.json` file in using a web server with a domain that you own. This file tells the mobile browser which Android application to open instead of the browser. To create the file, get the package name of the Flutter app you created in the previous step and the sha256 fingerprint of the signing key you will be using to build the APK. ### Package name Locate the package name in `AndroidManifest.xml`, the `package` property under `<manifest>` tag. Package names are usually in the format of `com.example.*`. ### sha256 fingerprint The process might differ depending on how the apk is signed. #### Using google play app signing You can find the sha256 fingerprint directly from play developer console. Open your app in the play console, under **Release> Setup > App Integrity> App Signing tab**: <img src="/assets/images/docs/cookbook/set-up-app-links-pdc-signing-key.png" alt="Screenshot of sha256 fingerprint in play developer console" width="50%" /> #### Using local keystore If you are storing the key locally, you can generate sha256 using the following command: ``` keytool -list -v -keystore <path-to-keystore> ``` ### assetlinks.json The hosted file should look similar to this: ```json [{ "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "android_app", "package_name": "com.example.deeplink_cookbook", "sha256_cert_fingerprints": ["FF:2A:CF:7B:DD:CC:F1:03:3E:E8:B2:27:7C:A2:E3:3C:DE:13:DB:AC:8E:EB:3A:B9:72:A1:0E:26:8A:F5:EC:AF"] } }] ``` 1. Set the `package_name` value to your Android application ID. 2. Set sha256_cert_fingerprints to the value you got from the previous step. 3. Host the file at a URL that resembles the following: `<webdomain>/.well-known/assetlinks.json` 4. Verify that your browser can access this file. ## Testing You can use a real device or the Emulator to test an app link, but first make sure you have executed `flutter run` at least once on the devices. This ensures that the Flutter application is installed. <img src="/assets/images/docs/cookbook/set-up-app-links-emulator-installed.png" alt="Emulator screenshot" width="50%" /> To test **only** the app setup, use the adb command: ``` adb shell 'am start -a android.intent.action.VIEW \ -c android.intent.category.BROWSABLE \ -d "http://<web-domain>/details"' \ <package name> ``` {{site.alert.note}} This doesn't test whether the web files are hosted correctly, the command launches the app even if web files are not presented. {{site.alert.end}} To test **both** web and app setup, you must click a link directly through web browser or another app. One way is to create a Google Doc, add the link, and tap on it. If everything is set up correctly, the Flutter application launches and displays the details screen: <img src="/assets/images/docs/cookbook/set-up-app-links-emulator-deeplinked.png" alt="Deeplinked Emulator screenshot" width="50%" /> ## Appendix Source code: [deeplink_cookbook][] [deeplink_cookbook]: {{site.github}}/flutter/codelabs/tree/main/deeplink_cookbook [Firebase Hosting]: {{site.firebase}}/docs/hosting [go_router]: {{site.pub}}/packages/go_router [GitHub Pages]: https://pages.github.com [uni_links]: {{site.pub}}/packages/uni_links [Signing the app]: /deployment/android#signing-the-app
website/src/cookbook/navigation/set-up-app-links.md/0
{ "file_path": "website/src/cookbook/navigation/set-up-app-links.md", "repo_id": "website", "token_count": 2352 }
1,298
--- title: Take a picture using the camera description: How to use a camera plugin on mobile. --- <?code-excerpt path-base="cookbook/plugins/picture_using_camera/"?> Many apps require working with the device's cameras to take photos and videos. Flutter provides the [`camera`][] plugin for this purpose. The `camera` plugin provides tools to get a list of the available cameras, display a preview coming from a specific camera, and take photos or videos. This recipe demonstrates how to use the `camera` plugin to display a preview, take a photo, and display it using the following steps: 1. Add the required dependencies. 2. Get a list of the available cameras. 3. Create and initialize the `CameraController`. 4. Use a `CameraPreview` to display the camera's feed. 5. Take a picture with the `CameraController`. 6. Display the picture with an `Image` widget. ## 1. Add the required dependencies To complete this recipe, you need to add three dependencies to your app: [`camera`][] : Provides tools to work with the cameras on the device. [`path_provider`][] : Finds the correct paths to store images. [`path`][] : Creates paths that work on any platform. To add the packages as dependencies, run `flutter pub add`: ```terminal $ flutter pub add camera path_provider path ``` {{site.alert.tip}} - For android, You must update `minSdkVersion` to 21 (or higher). - On iOS, lines below have to be added inside `ios/Runner/Info.plist` in order the access the camera and microphone. ``` <key>NSCameraUsageDescription</key> <string>Explanation on why the camera access is needed.</string> <key>NSMicrophoneUsageDescription</key> <string>Explanation on why the microphone access is needed.</string> ``` {{site.alert.end}} ## 2. Get a list of the available cameras Next, get a list of available cameras using the `camera` plugin. <?code-excerpt "lib/main.dart (init)"?> ```dart // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; ``` ## 3. Create and initialize the `CameraController` Once you have a camera, use the following steps to create and initialize a `CameraController`. This process establishes a connection to the device's camera that allows you to control the camera and display a preview of the camera's feed. 1. Create a `StatefulWidget` with a companion `State` class. 2. Add a variable to the `State` class to store the `CameraController`. 3. Add a variable to the `State` class to store the `Future` returned from `CameraController.initialize()`. 4. Create and initialize the controller in the `initState()` method. 5. Dispose of the controller in the `dispose()` method. <?code-excerpt "lib/main_step3.dart (controller)"?> ```dart // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({ super.key, required this.camera, }); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // Fill this out in the next steps. return Container(); } } ``` {{site.alert.warning}} If you do not initialize the `CameraController`, you *cannot* use the camera to display a preview and take pictures. {{site.alert.end}} ## 4. Use a `CameraPreview` to display the camera's feed Next, use the `CameraPreview` widget from the `camera` package to display a preview of the camera's feed. {{site.alert.secondary}} **Remember** You must wait until the controller has finished initializing before working with the camera. Therefore, you must wait for the `_initializeControllerFuture()` created in the previous step to complete before showing a `CameraPreview`. {{site.alert.end}} Use a [`FutureBuilder`][] for exactly this purpose. <?code-excerpt "lib/main.dart (FutureBuilder)" replace="/body: //g;/,$//g"?> ```dart // You must wait until the controller is initialized before displaying the // camera preview. Use a FutureBuilder to display a loading spinner until the // controller has finished initializing. FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { // If the Future is complete, display the preview. return CameraPreview(_controller); } else { // Otherwise, display a loading indicator. return const Center(child: CircularProgressIndicator()); } }, ) ``` ## 5. Take a picture with the `CameraController` You can use the `CameraController` to take pictures using the [`takePicture()`][] method, which returns an [`XFile`][], a cross-platform, simplified `File` abstraction. On both Android and IOS, the new image is stored in their respective cache directories, and the `path` to that location is returned in the `XFile`. In this example, create a `FloatingActionButton` that takes a picture using the `CameraController` when a user taps on the button. Taking a picture requires 2 steps: 1. Ensure that the camera is initialized. 2. Use the controller to take a picture and ensure that it returns a `Future<XFile>`. It is good practice to wrap these operations in a `try / catch` block in order to handle any errors that might occur. <?code-excerpt "lib/main_step5.dart (FAB)" replace="/^floatingActionButton: //g;/,$//g"?> ```dart FloatingActionButton( // Provide an onPressed callback. onPressed: () async { // Take the Picture in a try / catch block. If anything goes wrong, // catch the error. try { // Ensure that the camera is initialized. await _initializeControllerFuture; // Attempt to take a picture and then get the location // where the image file is saved. final image = await _controller.takePicture(); } catch (e) { // If an error occurs, log the error to the console. print(e); } }, child: const Icon(Icons.camera_alt), ) ``` ## 6. Display the picture with an `Image` widget If you take the picture successfully, you can then display the saved picture using an `Image` widget. In this case, the picture is stored as a file on the device. Therefore, you must provide a `File` to the `Image.file` constructor. You can create an instance of the `File` class by passing the path created in the previous step. <?code-excerpt "lib/image_file.dart (ImageFile)" replace="/^return\ //g"?> ```dart Image.file(File('path/to/my/picture.png')); ``` ## Complete example <?code-excerpt "lib/main.dart"?> ```dart import 'dart:async'; import 'dart:io'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; Future<void> main() async { // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.dark(), home: TakePictureScreen( // Pass the appropriate camera to the TakePictureScreen widget. camera: firstCamera, ), ), ); } // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({ super.key, required this.camera, }); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Take a picture')), // You must wait until the controller is initialized before displaying the // camera preview. Use a FutureBuilder to display a loading spinner until the // controller has finished initializing. body: FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { // If the Future is complete, display the preview. return CameraPreview(_controller); } else { // Otherwise, display a loading indicator. return const Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( // Provide an onPressed callback. onPressed: () async { // Take the Picture in a try / catch block. If anything goes wrong, // catch the error. try { // Ensure that the camera is initialized. await _initializeControllerFuture; // Attempt to take a picture and get the file `image` // where it was saved. final image = await _controller.takePicture(); if (!context.mounted) return; // If the picture was taken, display it on a new screen. await Navigator.of(context).push( MaterialPageRoute( builder: (context) => DisplayPictureScreen( // Pass the automatically generated path to // the DisplayPictureScreen widget. imagePath: image.path, ), ), ); } catch (e) { // If an error occurs, log the error to the console. print(e); } }, child: const Icon(Icons.camera_alt), ), ); } } // A widget that displays the picture taken by the user. class DisplayPictureScreen extends StatelessWidget { final String imagePath; const DisplayPictureScreen({super.key, required this.imagePath}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Display the Picture')), // The image is stored as a file on the device. Use the `Image.file` // constructor with the given path to display the image. body: Image.file(File(imagePath)), ); } } ``` [`camera`]: {{site.pub-pkg}}/camera [`FutureBuilder`]: {{site.api}}/flutter/widgets/FutureBuilder-class.html [`path`]: {{site.pub-pkg}}/path [`path_provider`]: {{site.pub-pkg}}/path_provider [`takePicture()`]: {{site.pub}}/documentation/camera/latest/camera/CameraController/takePicture.html [`XFile`]: {{site.pub}}/documentation/cross_file/latest/cross_file/XFile-class.html
website/src/cookbook/plugins/picture-using-camera.md/0
{ "file_path": "website/src/cookbook/plugins/picture-using-camera.md", "repo_id": "website", "token_count": 3913 }
1,299
--- title: Google APIs description: How to use Google APIs with Flutter. --- <?code-excerpt path-base="googleapis/"?> The [Google APIs package][] exposes dozens of Google services that you can use from Dart projects. This page describes how to use APIs that interact with end-user data by using Google authentication. Examples of user-data APIs include [Calendar][], [Gmail][], [YouTube][], and Firebase. {{site.alert.info}} The only APIs you should use directly from your Flutter project are those that access user data using Google authentication. APIs that require [service accounts][] **should not** be used directly from a Flutter application. Doing so requires shipping service credentials as part of your application, which is not secure. To use these APIs, we recommend creating an intermediate service. {{site.alert.end}} To add authentication to Firebase explicitly, check out the [Add a user authentication flow to a Flutter app using FirebaseUI][fb-lab] codelab and the [Get Started with Firebase Authentication on Flutter][fb-auth] docs. [fb-lab]: {{site.firebase}}/codelabs/firebase-auth-in-flutter-apps [Calendar]: {{site.pub-api}}/googleapis/latest/calendar_v3/calendar_v3-library.html [fb-auth]: {{site.firebase}}/docs/auth/flutter/start [Gmail]: {{site.pub-api}}/googleapis/latest/gmail_v1/gmail_v1-library.html [Google APIs package]: {{site.pub-pkg}}/googleapis [service accounts]: https://cloud.google.com/iam/docs/service-account-overview [YouTube]: {{site.pub-api}}/googleapis/latest/youtube_v3/youtube_v3-library.html ## Overview To use Google APIs, follow these steps: 1. Pick the desired API 1. Enable the API 1. Authenticate user with the required scopes 1. Obtain an authenticated HTTP client 1. Create and use the desired API class ## 1. Pick the desired API The documentation for [package:googleapis][] lists each API as a separate Dart library&emdash;in a `name_version` format. Check out [`youtube_v3`][] as an example. Each library might provide many types, but there is one _root_ class that ends in `Api`. For YouTube, it's [`YouTubeApi`][]. Not only is the `Api` class the one you need to instantiate (see step 3), but it also exposes the scopes that represent the permissions needed to use the API. For example, the [Constants section][] of the `YouTubeApi` class lists the available scopes. To request access to read (but not write) an end-users YouTube data, authenticate the user with [`youtubeReadonlyScope`][]. <?code-excerpt "lib/main.dart (youtubeImport)"?> ```dart /// Provides the `YouTubeApi` class. import 'package:googleapis/youtube/v3.dart'; ``` [Constants section]: {{site.pub-api}}/googleapis/latest/youtube_v3/YouTubeApi-class.html#constants [package:googleapis]: {{site.pub-api}}/googleapis [`youtube_v3`]: {{site.pub-api}}/googleapis/latest/youtube_v3/youtube_v3-library.html [`YouTubeApi`]: {{site.pub-api}}/googleapis/latest/youtube_v3/YouTubeApi-class.html [`youtubeReadonlyScope`]: {{site.pub-api}}/googleapis/latest/youtube_v3/YouTubeApi/youtubeReadonlyScope-constant.html ## 2. Enable the API To use Google APIs you must have a Google account and a Google project. You also need to enable your desired API. This example enables [YouTube Data API v3][]. For details, see the [getting started instructions][]. [getting started instructions]: https://cloud.google.com/apis/docs/getting-started [YouTube Data API v3]: https://console.cloud.google.com/apis/library/youtube.googleapis.com ## 3. Authenticate the user with the required scopes Use the [google_sign_in][gsi-pkg] package to authenticate users with their Google identity. Configure signin for each platform you want to support. <?code-excerpt "lib/main.dart (googleImport)"?> ```dart /// Provides the `GoogleSignIn` class import 'package:google_sign_in/google_sign_in.dart'; ``` When instantiating the [`GoogleSignIn`][] class, provide the desired scopes as discussed in the previous section. <?code-excerpt "lib/main.dart (init)"?> ```dart final _googleSignIn = GoogleSignIn( scopes: <String>[YouTubeApi.youtubeReadonlyScope], ); ``` Follow the instructions provided by [`package:google_sign_in`][gsi-pkg] to allow a user to authenticate. Once authenticated, you must obtain an authenticated HTTP client. [gsi-pkg]: {{site.pub-pkg}}/google_sign_in [`GoogleSignIn`]: {{site.pub-api}}/google_sign_in/latest/google_sign_in/GoogleSignIn-class.html ## 4. Obtain an authenticated HTTP client The [extension_google_sign_in_as_googleapis_auth][] package provides an [extension method][] on `GoogleSignIn` called [`authenticatedClient`][]. <?code-excerpt "lib/main.dart (authImport)"?> ```dart import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart'; ``` Add a listener to [`onCurrentUserChanged`][] and when the event value isn't `null`, you can create an authenticated client. <?code-excerpt "lib/main.dart (signinCall)"?> ```dart var httpClient = (await _googleSignIn.authenticatedClient())!; ``` This [`Client`][] instance includes the necessary credentials when invoking Google API classes. [`authenticatedClient`]: {{site.pub-api}}/extension_google_sign_in_as_googleapis_auth/latest/extension_google_sign_in_as_googleapis_auth/GoogleApisGoogleSignInAuth/authenticatedClient.html [`Client`]: {{site.pub-api}}/http/latest/http/Client-class.html [extension_google_sign_in_as_googleapis_auth]: {{site.pub-pkg}}/extension_google_sign_in_as_googleapis_auth [extension method]: {{site.dart-site}}/guides/language/extension-methods [`onCurrentUserChanged`]: {{site.pub-api}}/google_sign_in/latest/google_sign_in/GoogleSignIn/onCurrentUserChanged.html ## 5. Create and use the desired API class Use the API to create the desired API type and call methods. For instance: <?code-excerpt "lib/main.dart (playlist)"?> ```dart var youTubeApi = YouTubeApi(httpClient); var favorites = await youTubeApi.playlistItems.list( ['snippet'], playlistId: 'LL', // Liked List ); ``` ## More information You might want to check out the following: * The [`extension_google_sign_in_as_googleapis_auth` example][auth-ex] is a working implementation of the concepts described on this page. [auth-ex]: {{site.pub-pkg}}/extension_google_sign_in_as_googleapis_auth/example
website/src/data-and-backend/google-apis.md/0
{ "file_path": "website/src/data-and-backend/google-apis.md", "repo_id": "website", "token_count": 2006 }
1,300
--- title: Build and release an iOS app description: How to release a Flutter app to the App Store. short-title: iOS --- This guide provides a step-by-step walkthrough of releasing a Flutter app to the [App Store][appstore] and [TestFlight][]. ## Preliminaries Xcode is required to build and release your app. You must use a device running macOS to follow this guide. Before beginning the process of releasing your app, ensure that it meets Apple's [App Review Guidelines][appreview]. To publish your app to the App Store, you must first enroll in the [Apple Developer Program][devprogram]. You can read more about the various membership options in Apple's [Choosing a Membership][devprogram_membership] guide. ## Video overview For those who prefer video over text, the following video covers the same material as this guide. <iframe width="560" height="315" src="{{site.yt.embed}}/iE2bpP56QKc?si=tHqWYKNTN1H8H9mC" title="Release an iOS app with Flutter in 7 steps" {{site.yt.set}}></iframe> [Release an iOS app with Flutter in 7 steps]({{site.yt.watch}}?v=iE2bpP56QKc) ## Register your app on App Store Connect Manage your app's life cycle on [App Store Connect][appstoreconnect] (formerly iTunes Connect). You define your app name and description, add screenshots, set pricing, and manage releases to the App Store and TestFlight. Registering your app involves two steps: registering a unique Bundle ID, and creating an application record on App Store Connect. For a detailed overview of App Store Connect, see the [App Store Connect][appstoreconnect_guide] guide. ### Register a Bundle ID Every iOS application is associated with a Bundle ID, a unique identifier registered with Apple. To register a Bundle ID for your app, follow these steps: 1. Open the [App IDs][devportal_appids] page of your developer account. 1. Click **+** to create a new Bundle ID. 1. Enter an app name, select **Explicit App ID**, and enter an ID. 1. Select the services your app uses, then click **Continue**. 1. On the next page, confirm the details and click **Register** to register your Bundle ID. ### Create an application record on App Store Connect Register your app on App Store Connect: 1. Open [App Store Connect][appstoreconnect_login] in your browser. 1. On the App Store Connect landing page, click **My Apps**. 1. Click **+** in the top-left corner of the My Apps page, then select **New App**. 1. Fill in your app details in the form that appears. In the Platforms section, ensure that iOS is checked. Since Flutter does not currently support tvOS, leave that checkbox unchecked. Click **Create**. 1. Navigate to the application details for your app and select **App Information** from the sidebar. 1. In the General Information section, select the Bundle ID you registered in the preceding step. For a detailed overview, see [Add an app to your account][appstoreconnect_guide_register]. ## Review Xcode project settings This step covers reviewing the most important settings in the Xcode workspace. For detailed procedures and descriptions, see [Prepare for app distribution][distributionguide_config]. Navigate to your target's settings in Xcode: 1. Open the default Xcode workspace in your project by running `open ios/Runner.xcworkspace` in a terminal window from your Flutter project directory. 1. To view your app's settings, select the **Runner** target in the Xcode navigator. Verify the most important settings. In the **Identity** section of the **General** tab: `Display Name` : The display name of your app. `Bundle Identifier` : The App ID you registered on App Store Connect. In the **Signing & Capabilities** tab: `Automatically manage signing` : Whether Xcode should automatically manage app signing and provisioning. This is set `true` by default, which should be sufficient for most apps. For more complex scenarios, see the [Code Signing Guide][codesigning_guide]. `Team` : Select the team associated with your registered Apple Developer account. If required, select **Add Account...**, then update this setting. In the **Deployment** section of the **Build Settings** tab: `iOS Deployment Target` : The minimum iOS version that your app supports. Flutter supports iOS 12 and later. If your app or plugins include Objective-C or Swift code that makes use of APIs newer than iOS 12, update this setting to the highest required version. The **General** tab of your project settings should resemble the following: ![Xcode Project Settings](/assets/images/docs/releaseguide/xcode_settings.png){:width="100%"} For a detailed overview of app signing, see [Create, export, and delete signing certificates][appsigning]. ## Updating the app's deployment version If you changed `Deployment Target` in your Xcode project, open `ios/Flutter/AppframeworkInfo.plist` in your Flutter app and update the `MinimumOSVersion` value to match. ## Add an app icon When a new Flutter app is created, a placeholder icon set is created. This step covers replacing these placeholder icons with your app's icons: 1. Review the [iOS App Icon][appicon] guidelines. 1. In the Xcode project navigator, select `Assets.xcassets` in the `Runner` folder. Update the placeholder icons with your own app icons. 1. Verify the icon has been replaced by running your app using `flutter run`. ## Add a launch image Similar to the app icon, you can also replace the placeholder launch image: 1. In the Xcode project navigator, select `Assets.xcassets` in the `Runner` folder. Update the placeholder launch image with your own launch image. 1. Verify the new launch image by hot restarting your app. (Don't use `hot reload`.) ## Create a build archive and upload to App Store Connect During development, you've been building, debugging, and testing with _debug_ builds. When you're ready to ship your app to users on the App Store or TestFlight, you need to prepare a _release_ build. ### Update the app's build and version numbers The default version number of the app is `1.0.0`. To update it, navigate to the `pubspec.yaml` file and update the following line: ```yaml version: 1.0.0+1 ``` The version number is three numbers separated by dots, such as `1.0.0` in the example above, followed by an optional build number such as `1` in the example above, separated by a `+`. Both the version and the build number can be overridden in `flutter build ipa` by specifying `--build-name` and `--build-number`, respectively. In iOS, `build-name` uses `CFBundleShortVersionString` while `build-number` uses `CFBundleVersion`. Read more about iOS versioning at [Core Foundation Keys][] on the Apple Developer's site. You can also override the `pubspec.yaml` build name and number in Xcode: 1. Open `Runner.xcworkspace` in your app's `ios` folder. 1. Select **Runner** in the Xcode project navigator, then select the **Runner** target in the settings view sidebar. 1. In the Identity section, update the **Version** to the user-facing version number you wish to publish. 1. In the Identity section, update the **Build** identifier to a unique build number used to track this build on App Store Connect. Each upload requires a unique build number. ### Create an app bundle Run `flutter build ipa` to produce an Xcode build archive (`.xcarchive` file) in your project's `build/ios/archive/` directory and an App Store app bundle (`.ipa` file) in `build/ios/ipa`. Consider adding the `--obfuscate` and `--split-debug-info` flags to [obfuscate your Dart code][] to make it more difficult to reverse engineer. If you are not distributing to the App Store, you can optionally choose a different [export method][app_bundle_export_method] by adding the option `--export-method ad-hoc`, `--export-method development` or `--export-method enterprise`. {{site.alert.note}} On versions of Flutter where `flutter build ipa --export-method` is unavailable, open `build/ios/archive/MyApp.xcarchive` and follow the instructions below to validate and distribute the app from Xcode. {{site.alert.end}} ### Upload the app bundle to App Store Connect Once the app bundle is created, upload it to [App Store Connect][appstoreconnect_login] by either: <ol markdown="1"> <li markdown="1"> Install and open the [Apple Transport macOS app][apple_transport_app]. Drag and drop the `build/ios/ipa/*.ipa` app bundle into the app. </li> <li markdown="1"> Or upload the app bundle from the command line by running: ```bash xcrun altool --upload-app --type ios -f build/ios/ipa/*.ipa --apiKey your_api_key --apiIssuer your_issuer_id ``` Run `man altool` for details about how to authenticate with the App Store Connect API key. </li> <li markdown="1"> Or open `build/ios/archive/MyApp.xcarchive` in Xcode. Click the **Validate App** button. If any issues are reported, address them and produce another build. You can reuse the same build ID until you upload an archive. After the archive has been successfully validated, click **Distribute App**. {{site.alert.note}} When you export your app at the end of **Distribute App**, Xcode will create a directory containing an IPA of your app and an `ExportOptions.plist` file. You can create new IPAs with the same options without launching Xcode by running `flutter build ipa --export-options-plist=path/to/ExportOptions.plist`. See `xcodebuild -h` for details about the keys in this property list. {{site.alert.end}} </li> </ol> You can follow the status of your build in the Activities tab of your app's details page on [App Store Connect][appstoreconnect_login]. You should receive an email within 30 minutes notifying you that your build has been validated and is available to release to testers on TestFlight. At this point you can choose whether to release on TestFlight, or go ahead and release your app to the App Store. For more details, see [Upload an app to App Store Connect][distributionguide_upload]. ## Create a build archive with Codemagic CLI tools This step covers creating a build archive and uploading your build to App Store Connect using Flutter build commands and [Codemagic CLI Tools][codemagic_cli_tools] executed in a terminal in the Flutter project directory. This allows you to create a build archive with full control of distribution certificates in a temporary keychain isolated from your login keychain. <ol markdown="1"> <li markdown="1"> Install the Codemagic CLI tools: ```bash pip3 install codemagic-cli-tools ``` </li> <li markdown="1"> You'll need to generate an [App Store Connect API Key][appstoreconnect_api_key] with App Manager access to automate operations with App Store Connect. To make subsequent commands more concise, set the following environment variables from the new key: issuer id, key id, and API key file. ```bash export APP_STORE_CONNECT_ISSUER_ID=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee export APP_STORE_CONNECT_KEY_IDENTIFIER=ABC1234567 export APP_STORE_CONNECT_PRIVATE_KEY=`cat /path/to/api/key/AuthKey_XXXYYYZZZ.p8` ``` </li> <li markdown="1"> You need to export or create an iOS Distribution certificate to code sign and package a build archive. If you have existing [certificates][devportal_certificates], you can export the private keys by executing the following command for each certificate: ```bash openssl pkcs12 -in <certificate_name>.p12 -nodes -nocerts | openssl rsa -out cert_key ``` Or you can create a new private key by executing the following command: ```bash ssh-keygen -t rsa -b 2048 -m PEM -f cert_key -q -N "" ``` Later, you can have CLI tools automatically create a new iOS Distribution from the private key. </li> <li markdown="1"> Set up a new temporary keychain to be used for code signing: ```bash keychain initialize ``` {{site.alert.secondary}} **Restore Login Keychain!** After running `keychain initialize` you **must** run the following:<br> `keychain use-login` This sets your login keychain as the default to avoid potential authentication issues with apps on your machine. {{site.alert.end}} </li> <li markdown="1"> Fetch the code signing files from App Store Connect: ```bash app-store-connect fetch-signing-files $(xcode-project detect-bundle-id) \ --platform IOS \ --type IOS_APP_STORE \ --certificate-key=@file:/path/to/cert_key \ --create ``` Where `cert_key` is either your exported iOS Distribution certificate private key or a new private key which automatically generates a new certificate. The certificate will be created from the private key if it doesn't exist in App Store Connect. </li> <li markdown="1"> Now add the fetched certificates to your keychain: ```bash keychain add-certificates ``` </li> <li markdown="1"> Update the Xcode project settings to use fetched code signing profiles: ```bash xcode-project use-profiles ``` </li> <li markdown="1"> Install Flutter dependencies: ```bash flutter packages pub get ``` </li> <li markdown="1"> Install CocoaPods dependencies: ```bash find . -name "Podfile" -execdir pod install \; ``` </li> <li markdown="1"> Build the Flutter the iOS project: ```bash flutter build ipa --release \ --export-options-plist=$HOME/export_options.plist ``` Note that `export_options.plist` is the output of the `xcode-project use-profiles` command. </li> <li markdown="1"> Publish the app to App Store Connect: ```bash app-store-connect publish \ --path $(find $(pwd) -name "*.ipa") ``` </li> <li markdown="1"> As mentioned earlier, don't forget to set your login keychain as the default to avoid authentication issues with apps on your machine: ```bash keychain use-login ``` </li> </ol> You should receive an email within 30 minutes notifying you that your build has been validated and is available to release to testers on TestFlight. At this point you can choose whether to release on TestFlight, or go ahead and release your app to the App Store. ## Release your app on TestFlight [TestFlight][] allows developers to push their apps to internal and external testers. This optional step covers releasing your build on TestFlight. 1. Navigate to the TestFlight tab of your app's application details page on [App Store Connect][appstoreconnect_login]. 1. Select **Internal Testing** in the sidebar. 1. Select the build to publish to testers, then click **Save**. 1. Add the email addresses of any internal testers. You can add additional internal users in the **Users and Roles** page of App Store Connect, available from the dropdown menu at the top of the page. For more details, see [Distribute an app using TestFlight] [distributionguide_testflight]. ## Release your app to the App Store When you're ready to release your app to the world, follow these steps to submit your app for review and release to the App Store: 1. Select **Pricing and Availability** from the sidebar of your app's application details page on [App Store Connect][appstoreconnect_login] and complete the required information. 1. Select the status from the sidebar. If this is the first release of this app, its status is **1.0 Prepare for Submission**. Complete all required fields. 1. Click **Submit for Review**. Apple notifies you when their app review process is complete. Your app is released according to the instructions you specified in the **Version Release** section. For more details, see [Distribute an app through the App Store][distributionguide_submit]. ## Troubleshooting The [Distribute your app][distributionguide] guide provides a detailed overview of the process of releasing an app to the App Store. [appicon]: {{site.apple-dev}}/design/human-interface-guidelines/app-icons/ [appreview]: {{site.apple-dev}}/app-store/review/ [appsigning]: https://help.apple.com/xcode/mac/current/#/dev154b28f09 [appstore]: {{site.apple-dev}}/app-store/submissions/ [appstoreconnect]: {{site.apple-dev}}/support/app-store-connect/ [appstoreconnect_api_key]: https://appstoreconnect.apple.com/access/api [appstoreconnect_guide]: {{site.apple-dev}}/support/app-store-connect/ [appstoreconnect_guide_register]: https://help.apple.com/app-store-connect/#/dev2cd126805 [appstoreconnect_login]: https://appstoreconnect.apple.com/ [codemagic_cli_tools]: {{site.github}}/codemagic-ci-cd/cli-tools [codesigning_guide]: {{site.apple-dev}}/library/content/documentation/Security/Conceptual/CodeSigningGuide/Introduction/Introduction.html [Core Foundation Keys]: {{site.apple-dev}}/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html [devportal_appids]: {{site.apple-dev}}/account/ios/identifier/bundle [devportal_certificates]: {{site.apple-dev}}/account/resources/certificates [devprogram]: {{site.apple-dev}}/programs/ [devprogram_membership]: {{site.apple-dev}}/support/compare-memberships/ [distributionguide]: https://help.apple.com/xcode/mac/current/#/devac02c5ab8 [distributionguide_config]: https://help.apple.com/xcode/mac/current/#/dev91fe7130a [distributionguide_submit]: https://help.apple.com/xcode/mac/current/#/dev067853c94 [distributionguide_testflight]: https://help.apple.com/xcode/mac/current/#/dev2539d985f [distributionguide_upload]: https://help.apple.com/xcode/mac/current/#/dev442d7f2ca [obfuscate your Dart code]: /deployment/obfuscate [TestFlight]: {{site.apple-dev}}/testflight/ [app_bundle_export_method]: https://help.apple.com/xcode/mac/current/#/dev31de635e5 [apple_transport_app]: https://apps.apple.com/us/app/transporter/id1450874784
website/src/deployment/ios.md/0
{ "file_path": "website/src/deployment/ios.md", "repo_id": "website", "token_count": 5030 }
1,301
--- title: Flutter for SwiftUI Developers description: Learn how to apply SwiftUI developer knowledge when building Flutter apps. --- <?code-excerpt path-base="get-started/flutter-for/ios_devs"?> {% assign sample_path = "blob/main/examples/get-started/flutter-for/ios_devs" %} SwiftUI developers who want to write mobile apps using Flutter should review this guide. It explains how to apply existing SwiftUI knowledge to Flutter. {{site.alert.note}} If you instead have experience building apps for iOS with UIKit, see [Flutter for UIKit developers][]. {{site.alert.end}} Flutter is a framework for building cross-platform applications that uses the Dart programming language. To understand some differences between programming with Dart and programming with Swift, see [Learning Dart as a Swift Developer][] and [Flutter concurrency for Swift developers][]. Your SwiftUI knowledge and experience are highly valuable when building with Flutter. {% comment %} TODO: Add talk about plugin system for interacting with OS and hardware when [iOS and Apple hardware interactions with Flutter][] is released. {% endcomment %} Flutter also makes a number of adaptations to app behavior when running on iOS and macOS. To learn how, see [Platform adaptations][]. {{site.alert.info}} To integrate Flutter code into an **existing** iOS app, check out [Add Flutter to existing app][]. {{site.alert.end}} This document can be used as a cookbook by jumping around and finding questions that are most relevant to your needs. This guide embeds sample code. You can test full working examples on DartPad or view them on GitHub. ## Overview As an introduction, watch the following video. It outlines how Flutter works on iOS and how to use Flutter to build iOS apps. <iframe class="full-width" src="{{site.yt.embed}}/ceMsPBbcEGg" title="Learn how to develop with Flutter as an iOS developer" {{site.yt.set}}></iframe> Flutter and SwiftUI code describes how the UI looks and works. Developers call this type of code a _declarative framework_. ### Views vs. Widgets **SwiftUI** represents UI components as _views_. You configure views using _modifiers_. ```swift Text("Hello, World!") // <-- This is a View .padding(10) // <-- This is a modifier of that View ``` **Flutter** represents UI components as _widgets_. Both views and widgets only exist until they need to be changed. These languages call this property _immutability_. SwiftUI represents a UI component property as a View modifier. By contrast, Flutter uses widgets for both UI components and their properties. {:.include-lang} ```dart Padding( // <-- This is a Widget padding: EdgeInsets.all(10.0), // <-- So is this child: Text("Hello, World!"), // <-- This, too ))); ``` To compose layouts, both SwiftUI and Flutter nest UI components within one another. SwiftUI nests Views while Flutter nests Widgets. ### Layout process **SwiftUI** lays out views using the following process: 1. The parent view proposes a size to its child view. 1. All subsequent child views: - propose a size to _their_ child's view - ask that child what size it wants 1. Each parent view renders its child view at the returned size. **Flutter** differs somewhat with its process: 1. The parent widget passes constraints down to its children. Constraints include minimum and maximum values for height and width. 1. The child tries to decide its size. It repeats the same process with its own list of children: - It informs its child of the child's constraints. - It asks its child what size it wishes to be. 1. The parent lays out the child. - If the requested size fits in the constraints, the parent uses that size. - If the requested size doesn't fit in the constraints, the parent limits the height, width, or both to fit in its constraints. Flutter differs from SwiftUI because the parent component can override the child's desired size. The widget cannot have any size it wants. It also cannot know or decide its position on screen as its parent makes that decision. To force a child widget to render at a specific size, the parent must set tight constraints. A constraint becomes tight when its constraint's minimum size value equals its maximum size value. In **SwiftUI**, views might expand to the available space or limit their size to that of its content. **Flutter** widgets behave in similar manner. However, in Flutter parent widgets can offer unbounded constraints. Unbounded constraints set their maximum values to infinity. {:.include-lang} ```dart UnboundedBox( child: Container( width: double.infinity, height: double.infinity, color: red), ) ``` If the child expands and it has unbounded constraints, Flutter returns an overflow warning: {:.include-lang} ```dart UnconstrainedBox( child: Container(color: red, width: 4000, height: 50), ) ``` <img src="/assets/images/docs/ui/layout/layout-14.png" alt="When parents pass unbounded constraints to children, and the children are expanding, then there is an overflow warning"> To learn how constraints work in Flutter, see [Understanding constraints][]. ### Design system Because Flutter targets multiple platforms, your app doesn't need to conform to any design system. Though this guide features [Material][] widgets, your Flutter app can use many different design systems: - Custom Material widgets - Community built widgets - Your own custom widgets - [Cupertino widgets][] that follow Apple's Human Interface Guidelines <iframe width="560" height="315" src="{{site.yt.embed}}/3PdUaidHc-E?rel=0" title="Learn about the Cupertino Flutter Package" {{site.yt.set}}></iframe> If you're looking for a great reference app that features a custom design system, check out [Wonderous][]. ## UI Basics This section covers the basics of UI development in Flutter and how it compares to SwiftUI. This includes how to start developing your app, display static text, create buttons, react to on-press events, display lists, grids, and more. ### Getting started In **SwiftUI**, you use `App` to start your app. ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { HomePage() } } } ``` Another common SwiftUI practice places the app body within a `struct` that conforms to the `View` protocol as follows: ```swift struct HomePage: View { var body: some View { Text("Hello, World!") } } ``` To start your **Flutter** app, pass in an instance of your app to the `runApp` function. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=d3d38ae68f7d6444421d0485a1fd02db">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/get_started.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/get_started.dart (main)"?> ```dart void main() { runApp(const MyApp()); } ``` `App` is a widget. The build method describes the part of the user interface it represents. It's common to begin your app with a [`WidgetApp`][] class, like [`CupertinoApp`][]. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=d3d38ae68f7d6444421d0485a1fd02db">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/get_started.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/get_started.dart (myapp)"?> ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { // Returns a CupertinoApp that, by default, // has the look and feel of an iOS app. return const CupertinoApp( home: HomePage(), ); } } ``` The widget used in `HomePage` might begin with the `Scaffold` class. `Scaffold` implements a basic layout structure for an app. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=d3d38ae68f7d6444421d0485a1fd02db">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/get_started.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/get_started.dart (homepage)"?> ```dart class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return const Scaffold( body: Center( child: Text( 'Hello, World!', ), ), ); } } ``` Note how Flutter uses the [`Center`][] widget. SwiftUI renders a view's contents in its center by default. That's not always the case with Flutter. `Scaffold` doesn't render its `body` widget at the center of the screen. To center the text, wrap it in a `Center` widget. To learn about different widgets and their default behaviors, check out the [Widget catalog][]. ### Adding Buttons In **SwiftUI**, you use the `Button` struct to create a button. {:.include-lang} ```swift Button("Do something") { // this closure gets called when your // button is tapped } ``` To achieve the same result in **Flutter**, use the `CupertinoButton` class: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=b776dfe43c91e580c66b2b93368745eb">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/text_button.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/text_button.dart (textbutton)"?> ```dart CupertinoButton( onPressed: () { // This closure is called when your button is tapped. }, child: const Text('Do something'), ) ``` **Flutter** gives you access to a variety of buttons with predefined styles. The [`CupertinoButton`][] class comes from the Cupertino library. Widgets in the Cupertino library use Apple's design system. ### Aligning components horizontally In **SwiftUI**, stack views play a big part in designing your layouts. Two separate structures allow you to create stacks: 1. `HStack` for horizontal stack views 2. `VStack` for vertical stack views The following SwiftUI view adds a globe image and text to a horizontal stack view: {:.include-lang} ```swift HStack { Image(systemName: "globe") Text("Hello, world!") } ``` **Flutter** uses [`Row`][] rather than `HStack`: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=5715d4f269f629d274ef1b0e9546853b">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/row.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/row.dart (row)"?> ```dart Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(CupertinoIcons.globe), Text('Hello, world!'), ], ), ``` The `Row` widget requires a `List<Widget>` in the `children` parameter. The `mainAxisAlignment` property tells Flutter how to position children with extra space. `MainAxisAlignment.center` positions children in the center of the main axis. For `Row`, the main axis is the horizontal axis. ### Aligning components vertically The following examples build on those in the previous section. In **SwiftUI**, you use `VStack` to arrange the components into a vertical pillar. {:.include-lang} ```swift VStack { Image(systemName: "globe") Text("Hello, world!") } ``` **Flutter** uses the same Dart code from the previous example, except it swaps [`Column`][] for `Row`: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=5e85473354959c0712f05e86d111c584">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/column.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/column.dart (column)"?> ```dart Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(CupertinoIcons.globe), Text('Hello, world!'), ], ), ``` ### Displaying a list view In **SwiftUI**, you use the `List` base component to display sequences of items. To display a sequence of model objects, make sure that the user can identify your model objects. To make an object identifiable, use the `Identifiable` protocol. {:.include-lang} ```swift struct Person: Identifiable { var name: String } var persons = [ Person(name: "Person 1"), Person(name: "Person 2"), Person(name: "Person 3"), ] struct ListWithPersons: View { let persons: [Person] var body: some View { List { ForEach(persons) { person in Text(person.name) } } } } ``` This resembles how **Flutter** prefers to build its list widgets. Flutter doesn't need the list items to be identifiable. You set the number of items to display then build a widget for each item. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=66e6728e204021e3b9e0190be50d014b">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/list.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/list.dart (SimpleList)"?> ```dart class Person { String name; Person(this.name); } var items = [ Person('Person 1'), Person('Person 2'), Person('Person 3'), ]; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return ListTile( title: Text(items[index].name), ); }, ), ); } } ``` Flutter has some caveats for lists: - The [`ListView`] widget has a builder method. This works like the `ForEach` within SwiftUI's `List` struct. - The `itemCount` parameter of the `ListView` sets how many items the `ListView` displays. - The `itemBuilder` has an index parameter that will be between zero and one less than itemCount. The previous example returned a [`ListTile`][] widget for each item. The `ListTile` widget includes properties like `height` and `font-size`. These properties help build a list. However, Flutter allows you to return almost any widget that represents your data. ### Displaying a grid When constructing non-conditional grids in **SwiftUI**, you use `Grid` with `GridRow`. {:.include-lang} ```swift Grid { GridRow { Text("Row 1") Image(systemName: "square.and.arrow.down") Image(systemName: "square.and.arrow.up") } GridRow { Text("Row 2") Image(systemName: "square.and.arrow.down") Image(systemName: "square.and.arrow.up") } } ``` To display grids in **Flutter**, use the [`GridView`] widget. This widget has various constructors. Each constructor has a similar goal, but uses different input parameters. The following example uses the `.builder()` initializer: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=4ac2d2433390042d25c97f1e819ec337">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/grid.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/grid.dart (GridExample)"?> ```dart const widgets = [ Text('Row 1'), Icon(CupertinoIcons.arrow_down_square), Icon(CupertinoIcons.arrow_up_square), Text('Row 2'), Icon(CupertinoIcons.arrow_down_square), Icon(CupertinoIcons.arrow_up_square), ]; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, mainAxisExtent: 40, ), itemCount: widgets.length, itemBuilder: (context, index) => widgets[index], ), ); } } ``` The `SliverGridDelegateWithFixedCrossAxisCount` delegate determines various parameters that the grid uses to lay out its components. This includes `crossAxisCount` that dictates the number of items displayed on each row. How SwiftUI's `Grid` and Flutter's `GridView` differ in that `Grid` requires `GridRow`. `GridView` uses the delegate to decide how the grid should lay out its components. ### Creating a scroll view In **SwiftUI**, you use `ScrollView` to create custom scrolling components. The following example displays a series of `PersonView` instances in a scrollable fashion. {:.include-lang} ```swift ScrollView { VStack(alignment: .leading) { ForEach(persons) { person in PersonView(person: person) } } } ``` To create a scrolling view, **Flutter** uses [`SingleChildScrollView`][]. In the following example, the function `mockPerson` mocks instances of the `Person` class to create the custom `PersonView` widget. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=63039c5371995ae53d971d613a936f7b">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/scroll.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/scroll.dart (ScrollExample)"?> ```dart SingleChildScrollView( child: Column( children: mockPersons .map( (person) => PersonView( person: person, ), ) .toList(), ), ), ``` ### Responsive and adaptive design In **SwiftUI**, you use `GeometryReader` to create relative view sizes. For example, you could: - Multiply `geometry.size.width` by some factor to set the _width_. - Use `GeometryReader` as a breakpoint to change the design of your app. You can also see if the size class has `.regular` or `.compact` using `horizontalSizeClass`. To create relative views in **Flutter**, you can use one of two options: - Get the `BoxConstraints` object in the [`LayoutBuilder`][] class. - Use the [`MediaQuery.of()`][] in your build functions to get the size and orientation of your current app. To learn more, check out [Creating responsive and adaptive apps][]. ### Managing state In **SwiftUI**, you use the `@State` property wrapper to represent the internal state of a SwiftUI view. {:.include-lang} ```swift struct ContentView: View { @State private var counter = 0; var body: some View { VStack{ Button("+") { counter+=1 } Text(String(counter)) } }} ``` **SwiftUI** also includes several options for more complex state management such as the `ObservableObject` protocol. **Flutter** manages local state using a [`StatefulWidget`][]. Implement a stateful widget with the following two classes: - a subclass of `StatefulWidget` - a subclass of `State` The `State` object stores the widget's state. To change a widget's state, call `setState()` from the `State` subclass to tell the framework to redraw the widget. The following example shows a part of a counter app: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=c5fcf5897c21456c518ea954c2587ada">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/state.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/state.dart (State)"?> ```dart class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('$_counter'), TextButton( onPressed: () => setState(() { _counter++; }), child: const Text('+'), ), ], ), ), ); } } ``` To learn more ways to manage state, check out [State management][]. ### Animations Two main types of UI animations exist. - Implicit that animated from a current value to a new target. - Explicit that animates when asked. #### Implicit Animation SwiftUI and Flutter take a similar approach to animation. In both frameworks, you specify parameters like `duration`, and `curve`. In **SwiftUI**, you use the `animate()` modifier to handle implicit animation. {:.include-lang} ```swift Button("Tap me!"){ angle += 45 } .rotationEffect(.degrees(angle)) .animation(.easeIn(duration: 1)) ``` **Flutter** includes widgets for implicit animation. This simplifies animating common widgets. Flutter names these widgets with the following format: `AnimatedFoo`. For example: To rotate a button, use the [`AnimatedRotation`][] class. This animates the `Transform.rotate` widget. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=4b9cfedfe9ca09baeb83456fdf7cbe32">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/simple_animation.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/simple_animation.dart (AnimatedButton)"?> ```dart AnimatedRotation( duration: const Duration(seconds: 1), turns: turns, curve: Curves.easeIn, child: TextButton( onPressed: () { setState(() { turns += .125; }); }, child: const Text('Tap me!')), ), ``` Flutter allows you to create custom implicit animations. To compose a new animated widget, use the [`TweenAnimationBuilder`][]. #### Explicit Animation For explicit animations, **SwiftUI** uses the `withAnimation()` function. **Flutter** includes explicitly animated widgets with names formatted like `FooTransition`. One example would be the [`RotationTransition`][] class. Flutter also allows you to create a custom explicit animation using `AnimatedWidget` or `AnimatedBuilder`. To learn more about animations in Flutter, see [Animations overview][]. ### Drawing on the Screen In **SwiftUI**, you use `CoreGraphics` to draw lines and shapes to the screen. **Flutter** has an API based on the `Canvas` class, with two classes that help you draw: 1. [`CustomPaint`][] that requires a painter: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=fccb26fc4bca4c08ca37931089a837e7">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/canvas.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/canvas.dart (CustomPaint)"?> ```dart CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), ``` 2. [`CustomPainter`][] that implements your algorithm to draw to the canvas. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=fccb26fc4bca4c08ca37931089a837e7">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/canvas.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/canvas.dart (CustomPainter)"?> ```dart class SignaturePainter extends CustomPainter { SignaturePainter(this.points); final List<Offset?> points; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; } ``` ## Navigation This section explains how to navigate between pages of an app, the push and pop mechanism, and more. ### Navigating between pages Developers build iOS and macOS apps with different pages called _navigation routes_. In **SwiftUI**, the `NavigationStack` represents this stack of pages. The following example creates an app that displays a list of persons. To display a person's details in a new navigation link, tap on that person. {:.include-lang} ```swift NavigationStack(path: $path) { List { ForEach(persons) { person in NavigationLink( person.name, value: person ) } } .navigationDestination(for: Person.self) { person in PersonView(person: person) } } ``` If you have a small **Flutter** app without complex linking, use [`Navigator`][] with named routes. After defining your navigation routes, call your navigation routes using their names. 1. Name each route in the class passed to the `runApp()` function. The following example uses `App`: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=5ae0624689958c4775b064d39d108d9e">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/navigation.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/navigation.dart (Routes)"?> ```dart // Defines the route name as a constant // so that it's reusable. const detailsPageRouteName = '/details'; class App extends StatelessWidget { const App({ super.key, }); @override Widget build(BuildContext context) { return CupertinoApp( home: const HomePage(), // The [routes] property defines the available named routes // and the widgets to build when navigating to those routes. routes: { detailsPageRouteName: (context) => const DetailsPage(), }, ); } } ``` The following sample generates a list of persons using `mockPersons()`. Tapping a person pushes the person's detail page to the `Navigator` using `pushNamed()`. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=5ae0624689958c4775b064d39d108d9e">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/navigation.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/navigation.dart (ListView)"?> ```dart ListView.builder( itemCount: mockPersons.length, itemBuilder: (context, index) { final person = mockPersons.elementAt(index); final age = '${person.age} years old'; return ListTile( title: Text(person.name), subtitle: Text(age), trailing: const Icon( Icons.arrow_forward_ios, ), onTap: () { // When a [ListTile] that represents a person is // tapped, push the detailsPageRouteName route // to the Navigator and pass the person's instance // to the route. Navigator.of(context).pushNamed( detailsPageRouteName, arguments: person, ); }, ); }, ), ``` 1. Define the `DetailsPage` widget that displays the details of each person. In Flutter, you can pass arguments into the widget when navigating to the new route. Extract the arguments using `ModalRoute.of()`: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=5ae0624689958c4775b064d39d108d9e">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/navigation.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/navigation.dart (DetailsPage)"?> ```dart class DetailsPage extends StatelessWidget { const DetailsPage({super.key}); @override Widget build(BuildContext context) { // Read the person instance from the arguments. final Person person = ModalRoute.of( context, )?.settings.arguments as Person; // Extract the age. final age = '${person.age} years old'; return Scaffold( // Display name and age. body: Column(children: [Text(person.name), Text(age)]), ); } } ``` To create more advanced navigation and routing requirements, use a routing package such as [go_router][]. To learn more, check out [Navigation and routing][]. ### Manually pop back In **SwiftUI**, you use the `dismiss` environment value to pop-back to the previous screen. {:.include-lang} ```swift Button("Pop back") { dismiss() } ``` In **Flutter**, use the `pop()` function of the `Navigator` class: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=0cf352feaeaea2eb107f784d879e480d">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/popback.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/popback.dart (PopBackExample)"?> ```dart TextButton( onPressed: () { // This code allows the // view to pop back to its presenter. Navigator.of(context).pop(); }, child: const Text('Pop back'), ), ``` ### Navigating to another app In **SwiftUI**, you use the `openURL` environment variable to open a URL to another application. {:.include-lang} ```swift @Environment(\.openURL) private var openUrl // View code goes here Button("Open website") { openUrl( URL( string: "https://google.com" )! ) } ``` In **Flutter**, use the [`url_launcher`][] plugin. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/openapp.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/openapp.dart (OpenAppExample)"?> ```dart CupertinoButton( onPressed: () async { await launchUrl( Uri.parse('https://google.com'), ); }, child: const Text( 'Open website', ), ), ``` ## Themes, styles, and media You can style Flutter apps with little effort. Styling includes switching between light and dark themes, changing the design of your text and UI components, and more. This section covers how to style your apps. ### Using dark mode In **SwiftUI**, you call the `preferredColorScheme()` function on a `View` to use dark mode. In **Flutter**, you can control light and dark mode at the app-level. To control the brightness mode, use the `theme` property of the `App` class: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=c446775c3224787e51fb18b054a08a1c">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/cupertino_themes.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/cupertino_themes.dart (Theme)"?> ```dart CupertinoApp( theme: CupertinoThemeData( brightness: Brightness.dark, ), home: HomePage(), ); ``` ### Styling text In **SwiftUI**, you use modifier functions to style text. For example, to change the font of a `Text` string, use the `font()` modifier: {:.include-lang} ```swift Text("Hello, world!") .font(.system(size: 30, weight: .heavy)) .foregroundColor(.yellow) ``` To style text in **Flutter**, add a `TextStyle` widget as the value of the `style` parameter of the `Text` widget. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=c446775c3224787e51fb18b054a08a1c">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/cupertino_themes.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/cupertino_themes.dart (StylingTextExample)"?> ```dart Text( 'Hello, world!', style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: CupertinoColors.systemYellow, ), ), ``` ### Styling buttons In **SwiftUI**, you use modifier functions to style buttons. {:.include-lang} ```swift Button("Do something") { // do something when button is tapped } .font(.system(size: 30, weight: .bold)) .background(Color.yellow) .foregroundColor(Color.blue) } ``` To style button widgets in **Flutter**, set the style of its child, or modify properties on the button itself. In the following example: - The `color` property of `CupertinoButton` sets its `color`. - The `color` property of the child `Text` widget sets the button text color. <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.dartpad}}/?id=8ffd244574c98f510c29712f6e6c2204">Test in DartPad</a> </li> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/stylingbutton.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/stylingbutton.dart (StylingButtonExample)"?> ```dart child: CupertinoButton( color: CupertinoColors.systemYellow, onPressed: () {}, padding: const EdgeInsets.all(16), child: const Text( 'Do something', style: TextStyle( color: CupertinoColors.systemBlue, fontSize: 30, fontWeight: FontWeight.bold, ), ), ), ``` ### Using custom fonts In **SwiftUI**, you can use a custom font in your app in two steps. First, add the font file to your SwiftUI project. After adding the file, use the `.font()` modifier to apply it to your UI components. {:.include-lang} ```swift Text("Hello") .font( Font.custom( "BungeeSpice-Regular", size: 40 ) ) ``` In **Flutter**, you control your resources with a file named `pubspec.yaml`. This file is platform agnostic. To add a custom font to your project, follow these steps: 1. Create a folder called `fonts` in the project's root directory. This optional step helps to organize your fonts. 1. Add your `.ttf`, `.otf`, or `.ttc` font file into the `fonts` folder. 1. Open the `pubspec.yaml` file within the project. 1. Find the `flutter` section. 1. Add your custom font(s) under the `fonts` section. ``` flutter: fonts: - family: BungeeSpice fonts: - asset: fonts/BungeeSpice-Regular.ttf ``` After you add the font to your project, you can use it as in the following example: <nav class="navbar bg-primary"> <ul class="navbar-nav navbar-code ml-auto"> <li class="nav-item"> <a class="btn btn-navbar-code" href="{{site.repo.this}}/{{sample_path}}/lib/stylingbutton.dart">View on GitHub</a> </li> </ul> </nav> <?code-excerpt "lib/stylingbutton.dart (CustomFont)"?> ```dart Text( 'Cupertino', style: TextStyle( fontSize: 40, fontFamily: 'BungeeSpice', ), ) ``` {{site.alert.note}} To download custom fonts to use in your apps, check out [Google Fonts](https://fonts.google.com). {{site.alert.end}} ### Bundling images in apps In **SwiftUI**, you first add the image files to `Assets.xcassets`, then use the `Image` view to display the images. To add images in **Flutter**, follow a method similar to how you added custom fonts. 1. Add an `images` folder to the root directory. 1. Add this asset to the `pubspec.yaml` file. ``` flutter: assets: - images/Blueberries.jpg ``` After adding your image, display it using the `Image` widget's `.asset()` constructor. This constructor: 1. Instantiates the given image using the provided path. 1. Reads the image from the assets bundled with your app. 1. Displays the image on the screen. To review a complete example, check out the [`Image`][] docs. ### Bundling videos in apps In **SwiftUI**, you bundle a local video file with your app in two steps. First, you import the `AVKit` framework, then you instantiate a `VideoPlayer` view. In **Flutter**, add the [video_player][] plugin to your project. This plugin allows you to create a video player that works on Android, iOS, and on the web from the same codebase. 1. Add the plugin to your app and add the video file to your project. 1. Add the asset to your `pubspec.yaml` file. 1. Use the `VideoPlayerController` class to load and play your video file. To review a complete walkthrough, check out the [video_player example][]. [Flutter for UIKit developers]: /get-started/flutter-for/uikit-devs [Add Flutter to existing app]: /add-to-app [Animations overview]: /ui/animations [Cupertino widgets]: /ui/widgets/cupertino [Flutter concurrency for Swift developers]: /get-started/flutter-for/dart-swift-concurrency [Navigation and routing]: /ui/navigation [Material]: {{site.material}}/develop/flutter/ [Platform adaptations]: /platform-integration/platform-adaptations [`url_launcher`]: {{site.pub-pkg}}/url_launcher [widget catalog]: /ui/widgets/layout [Understanding constraints]: /ui/layout/constraints [`WidgetApp`]: {{site.api}}/flutter/widgets/WidgetsApp-class.html [`CupertinoApp`]: {{site.api}}/flutter/cupertino/CupertinoApp-class.html [`Center`]: {{site.api}}/flutter/widgets/Center-class.html [`CupertinoButton`]: {{site.api}}/flutter/cupertino/CupertinoButton-class.html [`Row`]: {{site.api}}/flutter/widgets/Row-class.html [`Column`]: {{site.api}}/flutter/widgets/Column-class.html [Learning Dart as a Swift Developer]: {{site.dart-site}}/guides/language/coming-from/swift-to-dart [`ListView`]: {{site.api}}/flutter/widgets/ListView-class.html [`ListTile`]: {{site.api}}/flutter/widgets/ListTitle-class.html [`GridView`]: {{site.api}}/flutter/widgets/GridView-class.html [`SingleChildScrollView`]: {{site.api}}/flutter/widgets/SingleChildScrollView-class.html [`LayoutBuilder`]: {{site.api}}/flutter/widgets/LayoutBuilder-class.html [`AnimatedRotation`]: {{site.api}}/flutter/widgets/AnimatedRotation-class.html [`TweenAnimationBuilder`]: {{site.api}}/flutter/widgets/TweenAnimationBuilder-class.html [`RotationTransition`]: {{site.api}}/flutter/widgets/RotationTransition-class.html [`Navigator`]: {{site.api}}/flutter/widgets/Navigator-class.html [`StatefulWidget`]: {{site.api}}/flutter/widgets/StatefulWidget-class.html [State management]: /data-and-backend/state-mgmt [Wonderous]: https://flutter.gskinner.com/wonderous/?utm_source=flutterdocs&utm_medium=docs&utm_campaign=iosdevs [video_player]: {{site.pub-pkg}}/video_player [video_player example]: {{site.pub-pkg}}/video_player/example [Creating responsive and adaptive apps]: /ui/layout/responsive/adaptive-responsive [`MediaQuery.of()`]: {{site.api}}/flutter/widgets/MediaQuery-class.html [`CustomPaint`]: {{site.api}}/flutter/widgets/CustomPaint-class.html [`CustomPainter`]: {{site.api}}/flutter/rendering/CustomPainter-class.html [`Image`]: {{site.api}}/flutter/widgets/Image-class.html [go_router]: {{site.pub-pkg}}/go_router
website/src/get-started/flutter-for/swiftui-devs.md/0
{ "file_path": "website/src/get-started/flutter-for/swiftui-devs.md", "repo_id": "website", "token_count": 14863 }
1,302
## Get the Flutter SDK {#get-sdk} {% include docs/china-notice.md %} 1. Install the core development tools needed for Flutter: ```terminal $ sudo apt install clang cmake ninja-build pkg-config libgtk-3-dev ``` This downloads the compiler toolchain needed to compile apps for ChromeOS. 1. Download Flutter from the [Flutter repo][] on GitHub with the following command in your home directory: ```terminal $ git clone https://github.com/flutter/flutter.git -b stable ``` 1. Add the `flutter` tool to your path: ```terminal $ echo PATH="$PATH:`pwd`/flutter/bin" >> ~/.profile $ source ~/.profile ``` You are now ready to run Flutter commands! ### Run flutter doctor Run the following command to see if there are any dependencies you need to install to complete the setup (for verbose output, add the `-v` flag): ```terminal $ flutter doctor ``` This command checks your environment and displays a report to the terminal window. The Dart SDK is bundled with Flutter; it is not necessary to install Dart separately. Check the output carefully for other software you might need to install or further tasks to perform (shown in **bold** text). For example: <pre> [-] Android toolchain - develop for Android devices <strong>✗ Unable to locate Android SDK. Install Android Studio from: https://developer.android.com/studio/index.html</strong> </pre> The following sections describe how to perform these tasks and finish the setup process. Once you have installed any missing dependencies, run the `flutter doctor` command again to verify that you've set everything up correctly. {% include_relative _analytics.md %} [Flutter repo]: {{site.repo.flutter}}
website/src/get-started/install/_deprecated/_get-sdk-chromeos.md/0
{ "file_path": "website/src/get-started/install/_deprecated/_get-sdk-chromeos.md", "repo_id": "website", "token_count": 512 }
1,303
--- title: Start building Flutter native desktop apps on Linux description: Configure your system to develop Flutter desktop apps on Linux. short-title: Make Linux desktop apps target: desktop config: LinuxDesktop devos: Linux next: title: Create a test app path: /get-started/test-drive --- {% include docs/install/reqs/linux/base.md os=page.devos target=page.target -%} {% include docs/install/flutter-sdk.md os=page.devos target=page.target terminal='a shell' -%} {% include docs/install/flutter-doctor.md devos=page.devos target=page.target config=page.config -%} {% include docs/install/next-steps.md devos=page.devos target=page.target config=page.config -%}
website/src/get-started/install/linux/desktop.md/0
{ "file_path": "website/src/get-started/install/linux/desktop.md", "repo_id": "website", "token_count": 258 }
1,304
--- title: <Job Title> toc: false --- {% comment %} 1. Make a copy of this document within the `src/jobs` directory 2. Name it something representative of the role 3. Remove the leading underscore (_) to allow the document to be published 4. Specify the full job title in the front matter 5. Update the sections with a TODO, removing the TODO when complete 6. Adjust the "To apply" link if necessary {% endcomment %} ## About the team <TODO: Area Description> ## About the position <TODO: Role Description> ## Our values ### Mentorship Upon joining Google, you will be paired with a formal mentor, who will help guide you in the process of ramping up, forging relationships, and learning the systems you'll need to do your job. Your manager can also help you find mentors who can coach you as you navigate your career at Google. In addition to formal mentors, we work and train together so that we are always learning from one another, and we celebrate and support the career progression of our team members. ### Inclusion Here on the Flutter team and at Google, we embrace our differences and are [committed to furthering our culture of inclusion](https://flutter.dev/culture). In addition to groups like the [Flutteristas](https://flutteristas.org/), [Employee Resource Groups (ERGs)](https://diversity.google/commitments/) are employee-initiated networks for supporting underrepresented employees and their allies with shared values of creating belonging across their communities and Google. ### Work-Life Balance Our team also puts a high value on work-life balance. Striking a healthy balance between your personal and professional life is crucial to your happiness and success here, which is why we aren't focused on how many hours you spend at work or online. Instead, we're happy to offer a flexible schedule so you can have a more productive and well-balanced life—both in and outside of work. ## Job location <TODO: Location> ## Job responsibilities <TODO: Responsibilities> ## Qualifications ### Minimum qualifications <TODO: Minimum Qualifications> ### Preferred qualifications <TODO: Preferred Qualifications> ## To apply Please apply by [filling out the following form](https://flutter.dev/go/job).
website/src/jobs/_template.md/0
{ "file_path": "website/src/jobs/_template.md", "repo_id": "website", "token_count": 568 }
1,305
--- title: Improving rendering performance description: How to measure and evaluate your app's rendering performance. --- {% include docs/performance.md %} Rendering animations in your app is one of the most cited topics of interest when it comes to measuring performance. Thanks in part to Flutter's Skia engine and its ability to quickly create and dispose of widgets, Flutter applications are performant by default, so you only need to avoid common pitfalls to achieve excellent performance. ## General advice If you see janky (non-smooth) animations, make **sure** that you are profiling performance with an app built in _profile_ mode. The default Flutter build creates an app in _debug_ mode, which is not indicative of release performance. For information, see [Flutter's build modes][]. A couple common pitfalls: * Rebuilding far more of the UI than expected each frame. To track widget rebuilds, see [Show performance data][]. * Building a large list of children directly, rather than using a ListView. For more information on evaluating performance including information on common pitfalls, see the following docs: * [Performance best practices][] * [Flutter performance profiling][] ## Mobile-only advice Do you see noticeable jank on your mobile app, but only on the first run of an animation? If so, see [Reduce shader animation jank on mobile][]. [Reduce shader animation jank on mobile]: /perf/shader ## Web-only advice The following series of articles cover what the Flutter Material team learned when improving performance of the Flutter Gallery app on the web: * [Optimizing performance in Flutter web apps with tree shaking and deferred loading][shaking] * [Improving perceived performance with image placeholders, precaching, and disabled navigation transitions][images] * [Building performant Flutter widgets][] [Building performant Flutter widgets]: {{site.flutter-medium}}/building-performant-flutter-widgets-3b2558aa08fa [Flutter's build modes]: /testing/build-modes [Flutter performance profiling]: /perf/ui-performance [images]: {{site.flutter-medium}}/improving-perceived-performance-with-image-placeholders-precaching-and-disabled-navigation-6b3601087a2b [Performance best practices]: /perf/best-practices [shaking]: {{site.flutter-medium}}/optimizing-performance-in-flutter-web-apps-with-tree-shaking-and-deferred-loading-535fbe3cd674 [Show performance data]: /tools/android-studio#show-performance-data
website/src/perf/rendering-performance.md/0
{ "file_path": "website/src/perf/rendering-performance.md", "repo_id": "website", "token_count": 641 }
1,306
--- title: Hosting native Android views in your Flutter app with Platform Views short-title: Android platform-views description: Learn how to host native Android views in your Flutter app with Platform Views. --- <?code-excerpt path-base="development/platform_integration"?> Platform views allow you to embed native views in a Flutter app, so you can apply transforms, clips, and opacity to the native view from Dart. This allows you, for example, to use the native Google Maps from the Android SDK directly inside your Flutter app. {{site.alert.note}} This page discusses how to host your own native Android views within a Flutter app. If you'd like to embed native iOS views in your Flutter app, see [Hosting native iOS views][]. {{site.alert.end}} [Hosting native iOS views]: /platform-integration/ios/platform-views Flutter supports two modes: Hybrid composition and virtual displays. Which one to use depends on the use case. Let's take a look: * [Hybrid composition](#hybrid-composition) appends the native `android.view.View` to the view hierarchy. Therefore, keyboard handling, and accessibility work out of the box. Prior to Android 10, this mode might significantly reduce the frame throughput (FPS) of the Flutter UI. For more context, see [Performance](#performance). * [Virtual displays](#virtual-display) render the `android.view.View` instance to a texture, so it's not embedded within the Android Activity's view hierarchy. Certain platform interactions such as keyboard handling and accessibility features might not work. To create a platform view on Android, use the following steps: ### On the Dart side On the Dart side, create a `Widget` and add one of the following build implementations. #### Hybrid composition In your Dart file, for example `native_view_example.dart`, use the following instructions: 1. Add the following imports: <?code-excerpt "lib/platform_views/native_view_example_1.dart (Import)"?> ```dart import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; ``` 2. Implement a `build()` method: <?code-excerpt "lib/platform_views/native_view_example_1.dart (HybridCompositionWidget)"?> ```dart Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. const Map<String, dynamic> creationParams = <String, dynamic>{}; return PlatformViewLink( viewType: viewType, surfaceFactory: (context, controller) { return AndroidViewSurface( controller: controller as AndroidViewController, gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, onCreatePlatformView: (params) { return PlatformViewsService.initSurfaceAndroidView( id: params.id, viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), onFocus: () { params.onFocusChanged(true); }, ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, ); } ``` For more information, see the API docs for: * [`PlatformViewLink`][] * [`AndroidViewSurface`][] * [`PlatformViewsService`][] [`AndroidViewSurface`]: {{site.api}}/flutter/widgets/AndroidViewSurface-class.html [`PlatformViewLink`]: {{site.api}}/flutter/widgets/PlatformViewLink-class.html [`PlatformViewsService`]: {{site.api}}/flutter/services/PlatformViewsService-class.html #### Virtual display In your Dart file, for example `native_view_example.dart`, use the following instructions: 1. Add the following imports: <?code-excerpt "lib/platform_views/native_view_example_2.dart (Import)"?> ```dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; ``` 2. Implement a `build()` method: <?code-excerpt "lib/platform_views/native_view_example_2.dart (VirtualDisplayWidget)"?> ```dart Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. final Map<String, dynamic> creationParams = <String, dynamic>{}; return AndroidView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } ``` For more information, see the API docs for: * [`AndroidView`][] [`AndroidView`]: {{site.api}}/flutter/widgets/AndroidView-class.html ### On the platform side On the platform side, use the standard `io.flutter.plugin.platform` package in either Java or Kotlin: {% samplecode android-platform-views %} {% sample Kotlin %} In your native code, implement the following: Extend `io.flutter.plugin.platform.PlatformView` to provide a reference to the `android.view.View` (for example, `NativeView.kt`): ```kotlin package dev.flutter.example import android.content.Context import android.graphics.Color import android.view.View import android.widget.TextView import io.flutter.plugin.platform.PlatformView internal class NativeView(context: Context, id: Int, creationParams: Map<String?, Any?>?) : PlatformView { private val textView: TextView override fun getView(): View { return textView } override fun dispose() {} init { textView = TextView(context) textView.textSize = 72f textView.setBackgroundColor(Color.rgb(255, 255, 255)) textView.text = "Rendered on a native Android view (id: $id)" } } ``` Create a factory class that creates an instance of the `NativeView` created earlier (for example, `NativeViewFactory.kt`): ```kotlin package dev.flutter.example import android.content.Context import io.flutter.plugin.common.StandardMessageCodec import io.flutter.plugin.platform.PlatformView import io.flutter.plugin.platform.PlatformViewFactory class NativeViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) { override fun create(context: Context, viewId: Int, args: Any?): PlatformView { val creationParams = args as Map<String?, Any?>? return NativeView(context, viewId, creationParams) } } ``` Finally, register the platform view. You can do this in an app or a plugin. For app registration, modify the app's main activity (for example, `MainActivity.kt`): ```kotlin package dev.flutter.example import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine class MainActivity : FlutterActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) flutterEngine .platformViewsController .registry .registerViewFactory("<platform-view-type>", NativeViewFactory()) } } ``` For plugin registration, modify the plugin's main class (for example, `PlatformViewPlugin.kt`): ```kotlin package dev.flutter.plugin.example import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding class PlatformViewPlugin : FlutterPlugin { override fun onAttachedToEngine(binding: FlutterPluginBinding) { binding .platformViewRegistry .registerViewFactory("<platform-view-type>", NativeViewFactory()) } override fun onDetachedFromEngine(binding: FlutterPluginBinding) {} } ``` {% sample Java %} In your native code, implement the following: Extend `io.flutter.plugin.platform.PlatformView` to provide a reference to the `android.view.View` (for example, `NativeView.java`): ```java package dev.flutter.example; import android.content.Context; import android.graphics.Color; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.platform.PlatformView; import java.util.Map; class NativeView implements PlatformView { @NonNull private final TextView textView; NativeView(@NonNull Context context, int id, @Nullable Map<String, Object> creationParams) { textView = new TextView(context); textView.setTextSize(72); textView.setBackgroundColor(Color.rgb(255, 255, 255)); textView.setText("Rendered on a native Android view (id: " + id + ")"); } @NonNull @Override public View getView() { return textView; } @Override public void dispose() {} } ``` Create a factory class that creates an instance of the `NativeView` created earlier (for example, `NativeViewFactory.java`): ```java package dev.flutter.example; import android.content.Context; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugin.platform.PlatformViewFactory; import java.util.Map; class NativeViewFactory extends PlatformViewFactory { NativeViewFactory() { super(StandardMessageCodec.INSTANCE); } @NonNull @Override public PlatformView create(@NonNull Context context, int id, @Nullable Object args) { final Map<String, Object> creationParams = (Map<String, Object>) args; return new NativeView(context, id, creationParams); } } ``` Finally, register the platform view. You can do this in an app or a plugin. For app registration, modify the app's main activity (for example, `MainActivity.java`): ```java package dev.flutter.example; import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { flutterEngine .getPlatformViewsController() .getRegistry() .registerViewFactory("<platform-view-type>", new NativeViewFactory()); } } ``` For plugin registration, modify the plugin's main file (for example, `PlatformViewPlugin.java`): ```java package dev.flutter.plugin.example; import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin; public class PlatformViewPlugin implements FlutterPlugin { @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { binding .getPlatformViewRegistry() .registerViewFactory("<platform-view-type>", new NativeViewFactory()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} } ``` {% endsamplecode %} For more information, see the API docs for: * [`FlutterPlugin`][] * [`PlatformViewRegistry`][] * [`PlatformViewFactory`][] * [`PlatformView`][] [`FlutterPlugin`]: {{site.api}}/javadoc/io/flutter/embedding/engine/plugins/FlutterPlugin.html [`PlatformView`]: {{site.api}}/javadoc/io/flutter/plugin/platform/PlatformView.html [`PlatformViewFactory`]: {{site.api}}/javadoc/io/flutter/plugin/platform/PlatformViewFactory.html [`PlatformViewRegistry`]: {{site.api}}/javadoc/io/flutter/plugin/platform/PlatformViewRegistry.html Finally, modify your `build.gradle` file to require one of the minimal Android SDK versions: ```gradle android { defaultConfig { minSdkVersion 19 // if using hybrid composition minSdkVersion 20 // if using virtual display. } } ``` #### Manual view invalidation Certain Android Views do not invalidate themselves when their content changes. Some example views include `SurfaceView` and `SurfaceTexture`. When your Platform View includes these views you are required to manually invalidate the view after they have been drawn to (or more specifically: after the swap chain is flipped). Manual view invalidation is done by calling `invalidate` on the View or one of its parent views. [`AndroidViewSurface`]: {{site.api}}/flutter/widgets/AndroidViewSurface-class.html {% include docs/platform-view-perf.md %}
website/src/platform-integration/android/platform-views.md/0
{ "file_path": "website/src/platform-integration/android/platform-views.md", "repo_id": "website", "token_count": 4186 }
1,307
--- title: Hosting native iOS views in your Flutter app with Platform Views short-title: iOS platform-views description: Learn how to host native iOS views in your Flutter app with Platform Views. --- <?code-excerpt path-base="development/platform_integration"?> Platform views allow you to embed native views in a Flutter app, so you can apply transforms, clips, and opacity to the native view from Dart. This allows you, for example, to use the native Google Maps from the Android and iOS SDKs directly inside your Flutter app. {{site.alert.note}} This page discusses how to host your own native iOS views within a Flutter app. If you'd like to embed native Android views in your Flutter app, see [Hosting native Android views][]. {{site.alert.end}} [Hosting native Android views]: /platform-integration/android/platform-views iOS only uses Hybrid composition, which means that the native `UIView` is appended to the view hierarchy. To create a platform view on iOS, use the following instructions: ### On the Dart side On the Dart side, create a `Widget` and add the build implementation, as shown in the following steps. In the Dart widget file, make changes similar to those shown in `native_view_example.dart`: <ol markdown="1"> <li markdown="1">Add the following imports: <?code-excerpt "lib/platform_views/native_view_example_3.dart (import)"?> ```dart import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; ``` </li> <li markdown="1">Implement a `build()` method: <?code-excerpt "lib/platform_views/native_view_example_3.dart (iOSCompositionWidget)"?> ```dart Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. final Map<String, dynamic> creationParams = <String, dynamic>{}; return UiKitView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } ``` </li> </ol> For more information, see the API docs for: [`UIKitView`][]. [`UIKitView`]: {{site.api}}/flutter/widgets/UiKitView-class.html ### On the platform side On the platform side, use either Swift or Objective-C: {% samplecode ios-platform-views %} {% sample Swift %} Implement the factory and the platform view. The `FLNativeViewFactory` creates the platform view, and the platform view provides a reference to the `UIView`. For example, `FLNativeView.swift`: ```swift import Flutter import UIKit class FLNativeViewFactory: NSObject, FlutterPlatformViewFactory { private var messenger: FlutterBinaryMessenger init(messenger: FlutterBinaryMessenger) { self.messenger = messenger super.init() } func create( withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any? ) -> FlutterPlatformView { return FLNativeView( frame: frame, viewIdentifier: viewId, arguments: args, binaryMessenger: messenger) } /// Implementing this method is only necessary when the `arguments` in `createWithFrame` is not `nil`. public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol { return FlutterStandardMessageCodec.sharedInstance() } } class FLNativeView: NSObject, FlutterPlatformView { private var _view: UIView init( frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?, binaryMessenger messenger: FlutterBinaryMessenger? ) { _view = UIView() super.init() // iOS views can be created here createNativeView(view: _view) } func view() -> UIView { return _view } func createNativeView(view _view: UIView){ _view.backgroundColor = UIColor.blue let nativeLabel = UILabel() nativeLabel.text = "Native text from iOS" nativeLabel.textColor = UIColor.white nativeLabel.textAlignment = .center nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0) _view.addSubview(nativeLabel) } } ``` Finally, register the platform view. This can be done in an app or a plugin. For app registration, modify the App's `AppDelegate.swift`: ```swift import Flutter import UIKit @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) weak var registrar = self.registrar(forPlugin: "plugin-name") let factory = FLNativeViewFactory(messenger: registrar!.messenger()) self.registrar(forPlugin: "<plugin-name>")!.register( factory, withId: "<platform-view-type>") return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ``` For plugin registration, modify the plugin's main file (for example, `FLPlugin.swift`): ```swift import Flutter import UIKit class FLPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let factory = FLNativeViewFactory(messenger: registrar.messenger()) registrar.register(factory, withId: "<platform-view-type>") } } ``` {% sample Objective-C %} In Objective-C, add the headers for the factory and the platform view. For example, as shown in `FLNativeView.h`: ```objc #import <Flutter/Flutter.h> @interface FLNativeViewFactory : NSObject <FlutterPlatformViewFactory> - (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger; @end @interface FLNativeView : NSObject <FlutterPlatformView> - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger; - (UIView*)view; @end ``` Implement the factory and the platform view. The `FLNativeViewFactory` creates the platform view, and the platform view provides a reference to the `UIView`. For example, `FLNativeView.m`: ```objc #import "FLNativeView.h" @implementation FLNativeViewFactory { NSObject<FlutterBinaryMessenger>* _messenger; } - (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger { self = [super init]; if (self) { _messenger = messenger; } return self; } - (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args { return [[FLNativeView alloc] initWithFrame:frame viewIdentifier:viewId arguments:args binaryMessenger:_messenger]; } /// Implementing this method is only necessary when the `arguments` in `createWithFrame` is not `nil`. - (NSObject<FlutterMessageCodec>*)createArgsCodec { return [FlutterStandardMessageCodec sharedInstance]; } @end @implementation FLNativeView { UIView *_view; } - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger { if (self = [super init]) { _view = [[UIView alloc] init]; } return self; } - (UIView*)view { return _view; } @end ``` Finally, register the platform view. This can be done in an app or a plugin. For app registration, modify the App's `AppDelegate.m`: ```objc #import "AppDelegate.h" #import "FLNativeView.h" #import "GeneratedPluginRegistrant.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; NSObject<FlutterPluginRegistrar>* registrar = [self registrarForPlugin:@"plugin-name"]; FLNativeViewFactory* factory = [[FLNativeViewFactory alloc] initWithMessenger:registrar.messenger]; [[self registrarForPlugin:@"<plugin-name>"] registerViewFactory:factory withId:@"<platform-view-type>"]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end ``` For plugin registration, modify the main plugin file (for example, `FLPlugin.m`): ```objc #import <Flutter/Flutter.h> #import "FLNativeView.h" @interface FLPlugin : NSObject<FlutterPlugin> @end @implementation FLPlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar { FLNativeViewFactory* factory = [[FLNativeViewFactory alloc] initWithMessenger:registrar.messenger]; [registrar registerViewFactory:factory withId:@"<platform-view-type>"]; } @end ``` {% endsamplecode %} For more information, see the API docs for: * [`FlutterPlatformViewFactory`][] * [`FlutterPlatformView`][] * [`PlatformView`][] [`FlutterPlatformView`]: {{site.api}}/ios-embedder/protocol_flutter_platform_view-p.html [`FlutterPlatformViewFactory`]: {{site.api}}/ios-embedder/protocol_flutter_platform_view_factory-p.html [`PlatformView`]: {{site.api}}/javadoc/io/flutter/plugin/platform/PlatformView.html ## Putting it together When implementing the `build()` method in Dart, you can use [`defaultTargetPlatform`][] to detect the platform, and decide which widget to use: <?code-excerpt "lib/platform_views/native_view_example_3.dart (TogetherWidget)"?> ```dart Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. final Map<String, dynamic> creationParams = <String, dynamic>{}; switch (defaultTargetPlatform) { case TargetPlatform.android: // return widget on Android. case TargetPlatform.iOS: // return widget on iOS. default: throw UnsupportedError('Unsupported platform view'); } } ``` ## Performance Platform views in Flutter come with performance trade-offs. For example, in a typical Flutter app, the Flutter UI is composed on a dedicated raster thread. This allows Flutter apps to be fast, as the main platform thread is rarely blocked. When a platform view is rendered with hybrid composition, the Flutter UI is composed from the platform thread. The platform thread competes with other tasks like handling OS or plugin messages. When an iOS PlatformView is on screen, the screen refresh rate is capped at 80fps to avoid rendering janks. For complex cases, there are some techniques that can be used to mitigate performance issues. For example, you could use a placeholder texture while an animation is happening in Dart. In other words, if an animation is slow while a platform view is rendered, then consider taking a screenshot of the native view and rendering it as a texture. ## Composition limitations There are some limitations when composing iOS Platform Views. - The [`ShaderMask`][] and [`ColorFiltered`][] widgets are not supported. - The [`BackdropFilter`][] widget is supported, but there are some limitations on how it can be used. For more details, check out the [iOS Platform View Backdrop Filter Blur design doc][design-doc]. [`ShaderMask`]: {{site.api}}/flutter/foundation/ShaderMask.html [`ColorFiltered`]: {{site.api}}/flutter/foundation/ColorFiltered.html [`BackdropFilter`]: {{site.api}}/flutter/foundation/BackdropFilter.html [`defaultTargetPlatform`]: {{site.api}}/flutter/foundation/defaultTargetPlatform.html [design-doc]: {{site.main-url}}/go/ios-platformview-backdrop-filter-blur
website/src/platform-integration/ios/platform-views.md/0
{ "file_path": "website/src/platform-integration/ios/platform-views.md", "repo_id": "website", "token_count": 4131 }
1,308
--- title: Building a web application with Flutter description: Instructions for creating a Flutter app for the web. short-title: Web development --- This page covers the following steps for getting started with web support: * Configure the `flutter` tool for web support. * Create a new project with web support. * Run a new project with web support. * Build an app with web support. * Add web support to an existing project. ## Requirements To create a Flutter app with web support, you need the following software: * Flutter SDK. See the [Flutter SDK][] installation instructions. * [Chrome][]; debugging a web app requires the Chrome browser. * Optional: An IDE that supports Flutter. You can install [Visual Studio Code][], [Android Studio][], [IntelliJ IDEA][]. Also [install the Flutter and Dart plugins][] to enable language support and tools for refactoring, running, debugging, and reloading your web app within an editor. See [setting up an editor][] for more details. [Android Studio]: {{site.android-dev}}/studio [IntelliJ IDEA]: https://www.jetbrains.com/idea/ [Visual Studio Code]: https://code.visualstudio.com/ For more information, see the [web FAQ][]. ## Create a new project with web support You can use the following steps to create a new project with web support. ### Set up Run the following commands to use the latest version of the Flutter SDK: ```terminal $ flutter channel stable $ flutter upgrade ``` {{site.alert.warning}} Running `flutter channel stable` replaces your current version of Flutter with the stable version and can take time if your connection is slow. After this, running `flutter upgrade` upgrades your install to the latest `stable`. Returning to another channel (beta or master) requires calling `flutter channel <channel>` explicitly. {{site.alert.end}} If Chrome is installed, the `flutter devices` command outputs a `Chrome` device that opens the Chrome browser with your app running, and a `Web Server` that provides the URL serving the app. ```terminal $ flutter devices 1 connected device: Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150 ``` In your IDE, you should see **Chrome (web)** in the device pulldown. ### Create and run Creating a new project with web support is no different than [creating a new Flutter project][] for other platforms. #### IDE Create a new app in your IDE and it automatically creates iOS, Android, [desktop][], and web versions of your app. From the device pulldown, select **Chrome (web)** and run your app to see it launch in Chrome. #### Command line To create a new app that includes web support (in addition to mobile support), run the following commands, substituting `my_app` with the name of your project: ```terminal $ flutter create my_app $ cd my_app ``` To serve your app from `localhost` in Chrome, enter the following from the top of the package: ```terminal $ flutter run -d chrome ``` {{site.alert.note}} If there aren't any other connected devices, the `-d chrome` is optional. {{site.alert.end}} The `flutter run` command launches the application using the [development compiler] in a Chrome browser. {{site.alert.warning}} **Hot reload is not supported in a web browser** Currently, Flutter supports **hot restart**, but not **hot reload** in a web browser. {{site.alert.end}} ### Build Run the following command to generate a release build: ```terminal $ flutter build web ``` A release build uses [dart2js][] (instead of the [development compiler][]) to produce a single JavaScript file `main.dart.js`. You can create a release build using release mode (`flutter run --release`) or by using `flutter build web`. This populates a `build/web` directory with built files, including an `assets` directory, which need to be served together. You can also include `--web-renderer html` or `--web-renderer canvaskit` to select between the HTML or CanvasKit renderers, respectively. For more information, see [Web renderers][]. For more information, see [Build and release a web app][]. ## Add web support to an existing app To add web support to an existing project created using a previous version of Flutter, run the following command from your project's top-level directory: ```terminal $ flutter create --platforms web . ``` [Build and release a web app]: /deployment/web [creating a new Flutter project]: /get-started/test-drive [dart2js]: {{site.dart-site}}/tools/dart2js [desktop]: /platform-integration/desktop [development compiler]: {{site.dart-site}}/tools/dartdevc [file an issue]: {{site.repo.flutter}}/issues/new?title=[web]:+%3Cdescribe+issue+here%3E&labels=%E2%98%B8+platform-web&body=Describe+your+issue+and+include+the+command+you%27re+running,+flutter_web%20version,+browser+version [install the Flutter and Dart plugins]: /get-started/editor [setting up an editor]: /get-started/editor [web FAQ]: /platform-integration/web/faq [Chrome]: https://www.google.com/chrome/ [Flutter SDK]: /get-started/install [Web renderers]: /platform-integration/web/renderers
website/src/platform-integration/web/building.md/0
{ "file_path": "website/src/platform-integration/web/building.md", "repo_id": "website", "token_count": 1452 }
1,309
--- title: Building Windows apps with Flutter description: Platform-specific considerations for building for Windows with Flutter. toc: true short-title: Windows development --- This page discusses considerations unique to building Windows apps with Flutter, including shell integration and distribution of Windows apps through the Microsoft Store on Windows. ## Integrating with Windows The Windows programming interface combines traditional Win32 APIs, COM interfaces and more modern Windows Runtime libraries. As all these provide a C-based ABI, you can call into the services provided by the operating system using Dart's Foreign Function Interface library (`dart:ffi`). FFI is designed to enable Dart programs to efficiently call into C libraries. It provides Flutter apps with the ability to allocate native memory with `malloc` or `calloc`, support for pointers, structs and callbacks, and ABI types like `long` and `size_t`. For more information about calling C libraries from Flutter, see [C interop using `dart:ffi`]. In practice, while it is relatively straightforward to call basic Win32 APIs from Dart in this way, it is easier to use a wrapper library that abstracts the intricacies of the COM programming model. The [win32 package] provides a library for accessing thousands of common Windows APIs, using metadata provided by Microsoft for consistency and correctness. The package also includes examples of a variety of common use cases, such as WMI, disk management, shell integration, and system dialogs. A number of other packages build on this foundation, providing idiomatic Dart access for the [Windows registry], [gamepad support], [biometric storage], [taskbar integration], and [serial port access], to name a few. More generally, many other [packages support Windows], including common packages such as [`url_launcher`], [`shared_preferences`], [`file_selector`], and [`path_provider`]. [C interop using `dart:ffi`]: {{site.dart-site}}/guides/libraries/c-interop [win32 package]: {{site.pub}}/packages/win32 [Windows registry]: {{site.pub}}/packages/win32_registry [gamepad support]: {{site.pub}}/packages/win32_gamepad [biometric storage]: {{site.pub}}/packages/biometric_storage [taskbar integration]: {{site.pub}}//packages/windows_taskbar [serial port access]: {{site.pub}}/packages/serial_port_win32 [packages support Windows]: {{site.pub}}/packages?q=platform%3Awindows [`url_launcher`]: {{site.pub-pkg}}/url_launcher [`shared_preferences`]: {{site.pub-pkg}}/shared_preferences [`file_selector`]: {{site.pub-pkg}}/file_selector [`path_provider`]: {{site.pub-pkg}}/path_provider ## Supporting Windows UI guidelines While you can use any visual style or theme you choose, including Material, some app authors might wish to build an app that matches the conventions of Microsoft's [Fluent design system][]. The [fluent_ui][] package, a [Flutter Favorite][], provides support for visuals and common controls that are commonly found in modern Windows apps, including navigation views, content dialogs, flyouts, date pickers, and tree view widgets. In addition, Microsoft offers [fluentui_system_icons][], a package that provides easy access to thousands of Fluent icons for use in your Flutter app. Lastly, the [bitsdojo_window][] package provides support for "owner draw" title bars, allowing you to replace the standard Windows title bar with a custom one that matches the rest of your app. [Fluent design system]: https://docs.microsoft.com/en-us/windows/apps/design/ [fluent_ui]: {{site.pub}}/packages/fluent_ui [Flutter Favorite]: /packages-and-plugins/favorites [fluentui_system_icons]: {{site.pub}}/packages/fluentui_system_icons [bitsdojo_window]: {{site.pub}}/packages/bitsdojo_window ## Customizing the Windows host application When you create a Windows app, Flutter generates a small C++ application that hosts Flutter. This "runner app" is responsible for creating and sizing a traditional Win32 window, initializing the Flutter engine and any native plugins, and running the Windows message loop (passing relevant messages on to Flutter for further processing). You can, of course, make changes to this code to suit your needs, including modifying the app name and icon, and setting the window's initial size and location. The relevant code is in main.cpp, where you will find code similar to the following: ```cpp Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"myapp", origin, size)) { return EXIT_FAILURE; } ``` Replace `myapp` with the title you would like displayed in the Windows caption bar, as well as optionally adjusting the dimensions for size and the window coordinates. To change the Windows application icon, replace the `app_icon.ico` file in the `windows\runner\resources` directory with an icon of your preference. The generated Windows executable filename can be changed by editing the `BINARY_NAME` variable in `windows/CMakeLists.txt`: ```cmake cmake_minimum_required(VERSION 3.14) project(windows_desktop_app LANGUAGES CXX) # The name of the executable created for the application. # Change this to change the on-disk name of your application. set(BINARY_NAME "YourNewApp") cmake_policy(SET CMP0063 NEW) ``` When you run `flutter build windows`, the executable file generated in the `build\windows\runner\Release` directory will match the newly given name. Finally, further properties for the app executable itself can be found in the `Runner.rc` file in the `windows\runner` directory. Here you can change the copyright information and application version that is embedded in the Windows app, which is displayed in the Windows Explorer properties dialog box. To change the version number, edit the `VERSION_AS_NUMBER` and `VERSION_AS_STRING` properties; other information can be edited in the `StringFileInfo` block. ## Compiling with Visual Studio For most apps, it's sufficient to allow Flutter to handle the compilation process using the `flutter run` and `flutter build` commands. If you are making significant changes to the runner app or integrating Flutter into an existing app, you might want to load or compile the Flutter app in Visual Studio itself. Follow these steps: 1. Run `flutter build windows` to create the `build\` directory. 1. Open the Visual Studio solution file for the Windows runner, which can now be found in the `build\windows` directory, named according to the parent Flutter app. 1. In Solution Explorer, you will see a number of projects. Right-click the one that has the same name as the Flutter app, and choose **Set as Startup Project**. 1. To generate the necessary dependencies, run **Build** > **Build Solution** You can also press/ <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>B</kbd>. To run the Windows app from Visual Studio, go to **Debug** > **Start Debugging**. You can also press <kbd>F5</kbd>. 1. Use the toolbar to switch between Debug and Release configurations as appropriate. ## Distributing Windows apps There are various approaches you can use for distributing your Windows application. Here are some options: * Use tooling to construct an MSIX installer (described in the next section) for your application and distribute it through the Microsoft Windows App Store. You don't need to manually create a signing certificate for this option as it is handled for you. * Construct an MSIX installer and distribute it through your own website. For this option, you need to give your application a digital signature in the form of a `.pfx` certificate. * Collect all of the necessary pieces and build your own zip file. ### MSIX packaging [MSIX][], the new Windows application package format, provides a modern packaging format and installer. This format can either be used to ship applications to the Microsoft Store on Windows, or you can distribute app installers directly. The easiest way to create an MSIX distribution for a Flutter project is to use the [`msix` pub package][msix package]. For an example of using the `msix` package from a Flutter desktop app, see the [Desktop Photo Search][] sample. [MSIX]: https://docs.microsoft.com/en-us/windows/msix/overview [msix package]: {{site.pub}}/packages/msix [Desktop Photo Search]: {{site.repo.samples}}/tree/main/desktop_photo_search #### Create a self-signed .pfx certificate for local testing For private deployment and testing with the help of the MSIX installer, you need to give your application a digital signature in the form of a `.pfx` certificate. For deployment through the Windows Store, generating a `.pfx` certificate is not required. The Windows Store handles creation and management of certificates for applications distributed through its store. Distributing your application by self hosting it on a website requires a certificate signed by a Certificate Authority known to Windows. Use the following instructions to generate a self-signed `.pfx` certificate. 1. If you haven't already, download the [OpenSSL][] toolkit to generate your certificates. 1. Go to where you installed OpenSSL, for example, `C:\Program Files\OpenSSL-Win64\bin`. 1. Set an environment variable so that you can access `OpenSSL` from anywhere:<br> `"C:\Program Files\OpenSSL-Win64\bin"` 1. Generate a private key as follows:<br> `openssl genrsa -out mykeyname.key 2048` 1. Generate a certificate signing request (CSR) file using the private key:<br> `openssl req -new -key mykeyname.key -out mycsrname.csr` 1. Generate the signed certificate (CRT) file using the private key and CSR file:<br> `openssl x509 -in mycsrname.csr -out mycrtname.crt -req -signkey mykeyname.key -days 10000` 1. Generate the `.pfx` file using the private key and CRT file:<br> `openssl pkcs12 -export -out CERTIFICATE.pfx -inkey mykeyname.key -in mycrtname.crt` 1. Install the `.pfx` certificate first on the local machine in `Certificate store` as `Trusted Root Certification Authorities` before installing the app. [OpenSSL]: https://slproweb.com/products/Win32OpenSSL.html ### Building your own zip file for Windows The Flutter executable, `.exe`, can be found in your project under `build\windows\runner\<build mode>\`. In addition to that executable, you need the following: * From the same directory: * all the `.dll` files * the `data` directory * The Visual C++ redistributables. You can use any of the methods shown in the [deployment example walkthroughs][] on the Microsoft site to ensure that end users have the C++ redistributables. If you use the `application-local` option, you need to copy: * `msvcp140.dll` * `vcruntime140.dll` * `vcruntime140_1.dll` Place the DLL files in the directory next to the executable and the other DLLs, and bundle them together in a zip file. The resulting structure looks something like this: ```text Release │ flutter_windows.dll │ msvcp140.dll │ my_app.exe │ vcruntime140.dll │ vcruntime140_1.dll │ └───data │ │ app.so │ │ icudtl.dat ... ``` At this point if desired it would be relatively simple to add this folder to a Windows installer such as Inno Setup, WiX, etc. [deployment example walkthroughs]: https://docs.microsoft.com/en-us/cpp/windows/deployment-examples
website/src/platform-integration/windows/building.md/0
{ "file_path": "website/src/platform-integration/windows/building.md", "repo_id": "website", "token_count": 3168 }
1,310
--- title: Deprecated API removed after v1.22 description: > After reaching end of life, the following deprecated APIs were removed from Flutter. --- ## Summary In accordance with Flutter's [Deprecation Policy][], deprecated APIs that reached end of life after the 1.22 stable release have been removed. This is the first time that deprecated APIs have been removed from Flutter, and some of these deprecations predate our migration guide policy. All affected APIs have been compiled into this primary source to aid in migration. A [quick reference sheet][] is available as well. A [design document][] and [article][] are available for more context on Flutter's deprecation policy. [Deprecation Policy]: {{site.repo.flutter}}/wiki/Tree-hygiene#deprecation [quick reference sheet]: /go/deprecations-removed-after-1-22 [design document]: /go/deprecation-lifetime [article]: {{site.flutter-medium}}/deprecation-lifetime-in-flutter-e4d76ee738ad ## Changes This section lists the deprecations, listed by the affected class. ### `CupertinoDialog` Supported by fix tool: IDE fix only. `CupertinoDialog` was deprecated in v0.2.3. Use `CupertinoAlertDialog` or `CupertinoPopupSurface` instead. **Migration guide** *CupertinoAlertDialog* Code before migration: ```dart CupertinoDialog(child: myWidget); ``` Code after migration: ```dart CupertinoAlertDialog(content: myWidget); ``` *CupertinoPopupSurface* Code before migration: ```dart CupertinoDialog(child: myWidget); ``` Code after migration: ```dart CupertinoPopupSurface(child: myWidget); ``` **References** API documentation: * [`CupertinoAlertDialog`][] * [`CupertinoPopupSurface`][] Relevant issues: * [Deprecate CupertinoDialog class][] Relevant PRs: * Deprecated in [#20649][] * Removed in [#73604][] [`CupertinoAlertDialog`]: {{site.api}}/flutter/cupertino/CupertinoAlertDialog-class.html [`CupertinoPopupSurface`]: {{site.api}}/flutter/cupertino/CupertinoPopupSurface-class.html [Deprecate CupertinoDialog class]: {{site.repo.flutter}}/issues/20397 [#20649]: {{site.repo.flutter}}/pull/20649 [#73604]: {{site.repo.flutter}}/pull/73604 --- ### Cupertino navigation bars' `actionsForegroundColor` Supported by fix tool: No `CupertinoNavigationBar.actionsForegroundColor` and `CupertinoSliverNavigationBar.actionsForegroundColor` were deprecated in v1.1.2. Setting `primaryColor` in your `CupertinoTheme` propagates this instead. To access the `primaryColor`, call `CupertinoTheme.of(context).primaryColor`. **Migration guide** Code before migration: ```dart CupertinoNavigationBar( actionsForegroundColor: CupertinoColors.systemBlue, ); CupertinoSliverNavigationBar( actionsForegroundColor: CupertinoColors.systemBlue, ); ``` Code after migration: ```dart CupertinoTheme( data: CupertinoThemeData( primaryColor: CupertinoColors.systemBlue ), child: ... ); // To access the color from the `CupertinoTheme` CupertinoTheme.of(context).primaryColor; ``` **References** API documentation: * [`CupertinoNavigationBar`][] * [`CupertinoSliverNavigationBar`][] * [`CupertinoTheme`][] * [`CupertinoThemeData`][] Relevant issues: * [Create a CupertinoApp and a CupertinoTheme][] Relevant PRs: * Deprecated in [#23759][] * Removed in [#73745][] [`CupertinoNavigationBar`]: {{site.api}}/flutter/cupertino/CupertinoNavigationBar-class.html [`CupertinoSliverNavigationBar`]: {{site.api}}/flutter/cupertino/CupertinoSliverNavigationBar-class.html [`CupertinoTheme`]: {{site.api}}/flutter/cupertino/CupertinoTheme-class.html [`CupertinoThemeData`]: {{site.api}}/flutter/cupertino/CupertinoThemeData-class.html [Create a CupertinoApp and a CupertinoTheme]: {{site.repo.flutter}}/issues/18037 [#23759]: {{site.repo.flutter}}/pull/23759 [#73745]: {{site.repo.flutter}}/pull/73745 --- ### `CupertinoTextThemeData.brightness` Supported by fix tool: Yes `CupertinoTextThemeData.brightness` was deprecated in v1.10.14. This field member was made ineffective at the time of deprecation. There is no replacement for this parameter, references should be removed. **Migration guide** Code before migration: ```dart const CupertinoTextThemeData themeData = CupertinoTextThemeData(brightness: Brightness.dark); themeData.copyWith(brightness: Brightness.light); ``` Code after migration: ```dart const CupertinoTextThemeData themeData = CupertinoTextThemeData(); themeData.copyWith(); ``` **References** API documentation: * [`CupertinoTextThemeData`][] Relevant issues: * [Revise CupertinoColors and CupertinoTheme for dynamic colors][] Relevant PRs: * Deprecated in [#41859][] * Removed in [#72017][] [`CupertinoTextThemeData`]: {{site.api}}/flutter/cupertino/CupertinoTextThemeData-class.html [Revise CupertinoColors and CupertinoTheme for dynamic colors]: {{site.repo.flutter}}/issues/35541 [#41859]: {{site.repo.flutter}}/pull/41859 [#72017]: {{site.repo.flutter}}/pull/72017 --- ### Pointer events constructed `fromHoverEvent` Supported by fix tool: Yes The `fromHoverEvent` constructors for `PointerEnterEvent` and `PointerExitEvent` were deprecated in v1.4.3. The `fromMouseEvent` constructor should be used instead. **Migration guide** Code before migration: ```dart final PointerEnterEvent enterEvent = PointerEnterEvent.fromHoverEvent(PointerHoverEvent()); final PointerExitEvent exitEvent = PointerExitEvent.fromHoverEvent(PointerHoverEvent()); ``` Code after migration: ```dart final PointerEnterEvent enterEvent = PointerEnterEvent.fromMouseEvent(PointerHoverEvent()); final PointerExitEvent exitEvent = PointerExitEvent.fromMouseEvent(PointerHoverEvent()); ``` **References** API documentation: * [`PointerEnterEvent`][] * [`PointerExitEvent`][] Relevant issues: * [PointerEnterEvent and PointerExitEvent can only be created from hover events][] Relevant PRs: * Deprecated in [#28602][] * Removed in [#72395][] [`PointerEnterEvent`]: {{site.api}}/flutter/gestures/PointerEnterEvent-class.html [`PointerExitEvent`]: {{site.api}}/flutter/gestures/PointerExitEvent-class.html [PointerEnterEvent and PointerExitEvent can only be created from hover events]: {{site.repo.flutter}}/issues/29696 [#28602]: {{site.repo.flutter}}/pull/28602 [#72395]: {{site.repo.flutter}}/pull/72395 --- ### `showDialog` uses `builder` Supported by fix tool: Yes The `child` parameter of `showDialog` was deprecated in v0.2.3. The `builder` parameter should be used instead. **Migration guide** Code before migration: ```dart showDialog(child: myWidget); ``` Code after migration: ```dart showDialog(builder: (context) => myWidget); ``` **References** API documentation: * [`showDialog`][] Relevant issues: * [showDialog should take a builder rather than a child][] Relevant PRs: * Deprecated in [#15303][] * Removed in [#72532][] [`showDialog`]: {{site.api}}/flutter/material/showDialog.html [showDialog should take a builder rather than a child]: {{site.repo.flutter}}/issues/14341 [#15303]: {{site.repo.flutter}}/pull/15303 [#72532]: {{site.repo.flutter}}/pull/72532 --- ### `Scaffold.resizeToAvoidBottomPadding` Supported by fix tool: Yes The `resizeToAvoidBottomPadding` parameter of `Scaffold` was deprecated in v1.1.9. The `resizeToAvoidBottomInset` parameter should be used instead. **Migration guide** Code before migration: ```dart Scaffold(resizeToAvoidBottomPadding: true); ``` Code after migration: ```dart Scaffold(resizeToAvoidBottomInset: true); ``` **References** API documentation: * [`Scaffold`][] Relevant issues: * [Show warning when nesting Scaffolds][] * [SafeArea with keyboard][] * [Double stacked material scaffolds shouldn't double resizeToAvoidBottomPadding][] * [viewInsets and padding on Window and MediaQueryData should define how they interact][] * [bottom overflow issue, when using textfields inside tabbarview][] Relevant PRs: * Deprecated in [#26259][] * Removed in [#72890][] [`Scaffold`]: {{site.api}}/flutter/material/Scaffold-class.html [Show warning when nesting Scaffolds]: {{site.repo.flutter}}/issues/23106 [SafeArea with keyboard]: {{site.repo.flutter}}/issues/25758 [Double stacked material scaffolds shouldn't double resizeToAvoidBottomPadding]: {{site.repo.flutter}}/issues/12084 [viewInsets and padding on Window and MediaQueryData should define how they interact]: {{site.repo.flutter}}/issues/15424 [bottom overflow issue, when using textfields inside tabbarview]: {{site.repo.flutter}}/issues/20295 [#26259]: {{site.repo.flutter}}/pull/26259 [#72890]: {{site.repo.flutter}}/pull/72890 --- ### `ButtonTheme.bar` Supported by fix tool: No The `bar` constructor of `ButtonTheme` was deprecated in v1.9.1. `ButtonBarTheme` can be used instead for `ButtonBar`s, or use another constructor of `ButtonTheme` if the use is not specific to `ButtonBar`. Button-specific theming is also available with the `TextButtonTheme`, `ElevatedButtonTheme`, and `OutlinedButtonTheme` classes, each corresponding with the appropriate button class, `TextButton`, `ElevatedButton` and `OutlinedButton`. **Migration guide** Code before migration: ```dart ButtonTheme.bar( minWidth: 10.0, alignedDropdown: true, height: 40.0, ); ``` Code after migration, using `ButtonTheme`: ```dart ButtonTheme( minWidth: 10.0, alignedDropdown: true, height: 40.0, ); ``` Code after migration, using `ButtonBarTheme`: ```dart ButtonBarTheme( data: ButtonBarThemeData( buttonMinWidth: 10.0, buttonAlignedDropdown: true, buttonHeight: 40.0, ) ); ``` **References** API documentation: * [`ButtonTheme`][] * [`ButtonBarTheme`][] * [`ButtonBar`][] * [`TextButtonTheme`][] * [`TextButton`][] * [`ElevatedButtonTheme`][] * [`ElevatedButton`][] * [`OutlinedButtonTheme`][] * [`OutlinedButton`][] Relevant issues: * [ButtonTheme.bar uses accent color when it should be using primary color][] * [ThemeData.accentColor has insufficient contrast for text][] * [Increased height as a result of changes to materialTapTargetSize affecting AlertDialog/ButtonBar heights][] Relevant PRs: * Deprecated in [#37544][] * Removed in [#73746][] [`ButtonTheme`]: {{site.api}}/flutter/material/ButtonTheme-class.html [`ButtonBarTheme`]: {{site.api}}/flutter/material/ButtonBarTheme-class.html [`ButtonBar`]: {{site.api}}/flutter/material/ButtonBar-class.html [`TextButtonTheme`]: {{site.api}}/flutter/material/TextButtonTheme-class.html [`TextButton`]: {{site.api}}/flutter/material/TextButton-class.html [`ElevatedButtonTheme`]: {{site.api}}/flutter/material/ElevatedButtonTheme-class.html [`ElevatedButton`]: {{site.api}}/flutter/material/ElevatedButton-class.html [`OutlinedButtonTheme`]: {{site.api}}/flutter/material/OutlinedButtonTheme-class.html [`OutlinedButton`]: {{site.api}}/flutter/material/OutlinedButton-class.html [ButtonTheme.bar uses accent color when it should be using primary color]: {{site.repo.flutter}}/issues/31333 [ThemeData.accentColor has insufficient contrast for text]: {{site.repo.flutter}}/issues/19946 [Increased height as a result of changes to materialTapTargetSize affecting AlertDialog/ButtonBar heights]: {{site.repo.flutter}}/issues/20585 [#37544]: {{site.repo.flutter}}/pull/37544 [#73746]: {{site.repo.flutter}}/pull/73746 --- ### `InlineSpan`, `TextSpan`, `PlaceholderSpan` Supported by fix tool: No The following methods were deprecated in the `InlineSpan`, `TextSpan` and `PlaceholderSpan` in order to enable embedding widgets inline into paragraphs, like images. **Migration guide** Code before migration | Code after migration -- | -- `InlineSpan.text` | `TextSpan.text` `InlineSpan.children` | `TextSpan.children` `InlineSpan.visitTextSpan` | `InlineSpan.visitChildren` `InlineSpan.recognizer` | `TextSpan.recognizer` `InlineSpan.describeSemantics` | `InlineSpan.computeSemanticsInformation` `PlaceholderSpan.visitTextSpan` | `PlaceHolderSpan.visitChildren` `TextSpan.visitTextSpan` | `TextSpan.visitChildren` **References** API documentation: * [`InlineSpan`][] * [`TextSpan`][] * [`PlaceholderSpan`][] * [`WidgetSpan`][] Relevant issues: * [Text: support inline images][] Relevant PRs: * Development history: * [#30069][] * [#33946][] * [#33794][] * Deprecated in [#34051][] * Removed in [#73747][] [`InlineSpan`]: {{site.api}}/flutter/painting/InlineSpan-class.html [`TextSpan`]: {{site.api}}/flutter/painting/TextSpan-class.html [`PlaceholderSpan`]: {{site.api}}/flutter/painting/PlaceholderSpan-class.html [`WidgetSpan`]: {{site.api}}/flutter/widgets/WidgetSpan-class.html [Text: support inline images]: {{site.repo.flutter}}/issues/2022 [#30069]: {{site.repo.flutter}}/pull/30069 [#33946]: {{site.repo.flutter}}/pull/33946 [#33794]: {{site.repo.flutter}}/pull/33794 [#34051]: {{site.repo.flutter}}/pull/34051 [#73747]: {{site.repo.flutter}}/pull/73747 --- ### `RenderView.scheduleInitialFrame` Supported by fix tool: No The `RenderView.scheduleInitialFrame` method was deprecated and removed in order to prevent splash screens from being taken down too early, resulting in a black screen. This would happen when `WidgetsFlutterBinding.ensureInitialized` was called. Instead, replace calls to this method with `RenderView.prepareInitialFrame`, followed by `RenderView.owner.requestVisualUpdate`. **Migration guide** Code before migration: ```dart scheduleInitialFrame(); ``` Code after migration: ```dart prepareInitialFrame(); owner.requestVisualUpdate(); ``` **References** API documentation: * [`RenderView`][] * [`WidgetsFlutterBinding`][] Relevant issues: * [WidgetsFlutterBinding.ensureInitialized() takes down splash screen too early][] Relevant PRs: * Deprecated in [#39535][] * Removed in [#73748][] [`RenderView`]: {{site.api}}/flutter/rendering/RenderView-class.html [`TextSpan`]: {{site.api}}/flutter/widgets/WidgetsFlutterBinding-class.html [`WidgetsFlutterBinding`]: {{site.api}}/flutter/widgets/WidgetsFlutterBinding-class.html [WidgetsFlutterBinding.ensureInitialized() takes down splash screen too early]: {{site.repo.flutter}}/issues/39494 [#39535]: {{site.repo.flutter}}/pull/39535 [#73748]: {{site.repo.flutter}}/pull/73748 --- ### `Layer.findAll` Supported by fix tool: No The `Layer.findAll` method was deprecated with the introduction of `Layer.findAnnotations` in order to unify the implementations of `find` and `findAll`. To migrate affected code, call `findAllAnnotations` instead. This method returns an `AnnotationResult`, containing the former return value of `findAll` in `AnnotationResult.annotations`. **Migration guide** Code before migration: ```dart findAll(offset); ``` Code after migration: ```dart findAllAnnotations(offset).annotations; ``` **References** API documentation: * [`Layer`][] * [`MouseRegion`][] * [`RenderMouseRegion`][] * [`AnnotatedRegionLayer`][] * [`AnnotationResult`][] Relevant issues: * [Breaking Proposal: MouseRegion defaults to opaque; Layers are required to implement findAnnotations][] Relevant PRs: * Initially changed in [#37896][] * Deprecated in [#42953][] * Removed in [#73749][] [`Layer`]: {{site.api}}/flutter/rendering/Layer-class.html [`MouseRegion`]: {{site.api}}/flutter/widgets/MouseRegion-class.html [`RenderMouseRegion`]: {{site.api}}/flutter/rendering/RenderMouseRegion-class.html [`AnnotatedRegionLayer`]: {{site.api}}/flutter/rendering/AnnotatedRegionLayer-class.html [`AnnotationResult`]: {{site.api}}/flutter/rendering/AnnotationResult-class.html [Breaking Proposal: MouseRegion defaults to opaque; Layers are required to implement findAnnotations]: {{site.repo.flutter}}/issues/38488 [#37896]: {{site.repo.flutter}}/pull/37896 [#42953]: {{site.repo.flutter}}/pull/42953 [#73749]: {{site.repo.flutter}}/pull/73749 --- ### `BinaryMessages` Supported by fix tool: No The `BinaryMessages` class, its associated static methods and the `defaultBinaryMessenger` getter were deprecated and removed. The `defaultBinaryMessenger` instance was moved to `ServicesBinding`. This made it possible to register a different default `BinaryMessenger` under testing environment, by creating a `ServicesBinding` subclass for testing. Doing so allows you to track the number of pending platform messages for synchronization purposes. **Migration guide** Code before migration: | Code after migration: -- | -- `defaultBinaryMessenger` | `ServicesBinding.instance.defaultBinaryMessenger` `BinaryMessages` | `BinaryMessenger` `BinaryMessages.handlePlatformMessage` | `ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage` `BinaryMessages.send` | `ServicesBinding.instance.defaultBinaryMessenger.send` `BinaryMessages.setMessageHandler` | `ServicesBinding.instance.defaultBinaryMessenger.setMessageHandler` `BinaryMessages.setMockMessageHandler` | `ServicesBinding.instance.defaultBinaryMessenger.setMockMessageHandler` **References** API documentation: * [`ServicesBinding`][] * [`BinaryMessenger`][] Relevant issues: * [Flutter synchronization support for Espresso/EarlGrey][] Relevant PRs: * Initially changed in [#37489][] * Deprecated in [#38464][] * Removed in [#73750][] [`ServicesBinding`]: {{site.api}}/flutter/services/ServicesBinding-mixin.html [`BinaryMessenger`]: {{site.api}}/flutter/services/BinaryMessenger-class.html [Flutter synchronization support for Espresso/EarlGrey]: {{site.repo.flutter}}/issues/37409 [#37489]: {{site.repo.flutter}}/pull/37489 [#38464]: {{site.repo.flutter}}/pull/38464 [#73750]: {{site.repo.flutter}}/pull/73750 --- ### Generic methods for `BuildContext` Supported by fix tool: Yes Several methods in `BuildContext` were using `Type` to search for ancestors. Most of those methods implied a cast at call site because their return type was a parent type. Moreover the type provided was not checked at analysis time even if the type is actually constrained. Making these methods generics improves type safety and requires less code. These method changes affect the `BuildContext`, `Element`, and `StatefulElement` classes. The `TypeMatcher` class was also removed. **Migration guide** Code before migration: ```dart ComplexLayoutState state = context.ancestorStateOfType(const TypeMatcher<ComplexLayoutState>()) as ComplexLayoutState; ``` Code after migration: ```dart ComplexLayoutState state = context.ancestorStateOfType<ComplexLayoutState>(); ``` `BuildContext` Code before migration: | Code after migration: -- | -- `inheritFromElement` | `dependOnInheritedElement` `inheritFromWidgetOfExactType` | `dependOnInheritedWidgetOfExactType` `ancestorInheritedElementForWidgetOfExactType` | `getElementForInheritedWidgetOfExactType` `ancestorWidgetOfExactType` | `findAncestorWidgetOfExactType` `ancestorStateOfType` | `findAncestorStateOfType` `rootAncestorStateOfType` | `findRootAncestorStateOfType` `ancestorRenderObjectOfType` | `findAncestorRenderObjectOfType` `Element` Code before migration: | Code after migration: -- | -- `inheritFromElement` | `dependOnInheritedElement` `inheritFromWidgetOfExactType` | `dependOnInheritedWidgetOfExactType` `ancestorInheritedElementForWidgetOfExactType` | `getElementForInheritedWidgetOfExactType` `ancestorWidgetOfExactType` | `findAncestorWidgetOfExactType` `ancestorStateOfType` | `findAncestorStateOfType` `rootAncestorStateOfType` | `findRootAncestorStateOfType` `ancestorRenderObjectOfType` | `findAncestorRenderObjectOfType` `StatefulElement` Code before migration: | Code after migration: -- | -- `inheritFromElement` | `dependOnInheritedElement` **References** API documentation: * [`Type`][] * [`BuildContext`][] * [`Element`][] * [`StatefulElement`][] Relevant PRs: * Deprecated in [#44189][] * Removed in: * [#69620][] * [#72903][] * [#72901][] * [#73751][] [`Type`]: {{site.api}}/flutter/dart-core/Type-class.html [`BuildContext`]: {{site.api}}/flutter/widgets/BuildContext-class.html [`Element`]: {{site.api}}/flutter/widgets/Element-class.html [`StatefulElement`]: {{site.api}}/flutter/widgets/StatefulElement-class.html [#44189]: {{site.repo.flutter}}/pull/44189 [#69620]: {{site.repo.flutter}}/pull/69620 [#72903]: {{site.repo.flutter}}/pull/72903 [#72901]: {{site.repo.flutter}}/pull/72901 [#73751]: {{site.repo.flutter}}/pull/73751 --- ### `WidgetsBinding.deferFirstFrameReport` & `WidgetsBinding.allowFirstFrameReport` Supported by fix tool: Yes The `deferFirstFrameReport` and `allowFirstFrameReport` methods of `WidgetsBinding` were deprecated and removed in order to provide the option to delay rendering the first frame. This is useful for widgets that need to obtain initialization information asynchronously and while they are waiting for that information no frame should render as that would take down the splash screen pre-maturely. The `deferFirstFrame` and `allowFirstFrame` methods should be used respectively instead. **Migration guide** Code before migration: ```dart final WidgetsBinding binding = WidgetsBinding.instance; binding.deferFirstFrameReport(); binding.allowFirstFrameReport(); ``` Code after migration: ```dart final WidgetsBinding binding = WidgetsBinding.instance; binding.deferFirstFrame(); binding.allowFirstFrame(); ``` **References** API documentation: * [`WidgetsBinding`][] Relevant PRs: * Initially changed in * [#45135][] * [#45588][] * Deprecated in [#45941][] * Removed in [#72893][] [`WidgetsBinding`]: {{site.api}}/flutter/widgets/WidgetsBinding-mixin.html [#45135]: {{site.repo.flutter}}/pull/45135 [#45588]: {{site.repo.flutter}}/pull/45588 [#45941]: {{site.repo.flutter}}/pull/45941 [#72893]: {{site.repo.flutter}}/pull/72893 --- ### `WaitUntilNoTransientCallbacks`, `WaitUntilNoPendingFrame`, & `WaitUntilFirstFrameRasterized` Supported by fix tool: No The `WaitUntilNoTransientCallbacks`, `WaitUntilNoPendingFrame`, and `WaitUntilFirstFrameRasterized` methods from the `flutter_driver` packages were deprecated and removed in order to provide a more composable `waitForCondition` API that can be used to compose conditions that the client would like to wait for. **Migration guide** Code before migration: | Code after migration: -- | -- `WaitUntilNoTransientCallbacks` | `WaitForCondition(NoTransientCallbacks())` `WaitUntilNoPendingFrame` | `WaitForCondition(NoPendingFrame())` `WaitUntilFirstFrameRasterized` | `WaitForCondition(FirstFrameRasterized))` **References** API documentation: * [`WaitForCondition`][] Relevant issues: * [Flutter synchronization support for Espresso/EarlGrey][] Relevant PRs: * Initially changed in [#37736][] * Deprecated in [#38836][] * Removed in [#73754][] [`WaitForCondition`]: {{site.api}}/flutter/flutter_driver/WaitForCondition-class.html [#37736]: {{site.repo.flutter}}/pull/37736 [#38836]: {{site.repo.flutter}}/pull/38836 [#73754]: {{site.repo.flutter}}/pull/73754 --- ## Timeline In stable release: 2.0.0
website/src/release/breaking-changes/1-22-deprecations.md/0
{ "file_path": "website/src/release/breaking-changes/1-22-deprecations.md", "repo_id": "website", "token_count": 7626 }
1,311
--- title: Android Predictive Back description: >- The ability to control back navigation at the time that a back gesture is received has been replaced with an ahead-of-time navigation API in order to support Android 14's Predictive Back feature. --- ## Summary To support Android 14's Predictive Back feature, a set of ahead-of-time APIs have replaced just-in-time navigation APIs, like `WillPopScope` and `Navigator.willPop`. ## Background Android 14 introduced the [Predictive Back feature]({{site.android-dev}}/guide/navigation/predictive-back-gesture), which allows the user to peek behind the current route during a valid back gesture and decide whether to continue back or to cancel the gesture. This was incompatible with Flutter's navigation APIs that allow the developer to cancel a back gesture after it is received. With predictive back, the back animation begins immediately when the user initiates the gesture and before it has been committed. There is no opportunity for the Flutter app to decide whether it's allowed to happen at that time. It must be known ahead of time. For this reason, all APIs that allow a Flutter app developer to cancel a back navigation at the time that a back gesture is received are now deprecated. They have been replaced with equivalent APIs that maintain a boolean state at all times that dictates whether or not back navigation is possible. When it is, the predictive back animation happens as usual. Otherwise, navigation is stopped. In both cases, the app developer is informed that a back was attempted and whether it was successful. ### `PopScope` The `PopScope` class directly replaces `WillPopScope`. Instead of deciding whether a pop is possible at the time it occurs, this is set ahead of time with the `canPop` boolean. You can still listen to pops by using `onPopInvoked`. ```dart PopScope( canPop: _myPopDisableEnableLogic(), onPopInvoked: (bool didPop) { // Handle the pop. If `didPop` is false, it was blocked. }, ) ``` ### `Form.canPop` and `Form.onPopInvoked` These two new parameters are based on `PopScope` and replace the deprecated `Form.onWillPop` parameter. They are used with `PopScope` in the same way as above. ```dart Form( canPop: _myPopDisableEnableLogic(), onPopInvoked: (bool didPop) { // Handle the pop. If `didPop` is false, it was blocked. }, ) ``` ### `Route.popDisposition` This getter synchronously returns the `RoutePopDisposition` for the route, which describes how pops will behave. ```dart if (myRoute.popDisposition == RoutePopDisposition.doNotPop) { // Back gestures are disabled. } ``` ### `ModalRoute.registerPopEntry` and `ModalRoute.unregisterPopEntry` Use these methods to register `PopScope` widgets, to be evaluated when the route decides whether it can pop. This functionality might be used when implementing a custom `PopScope` widget. ```dart @override void didChangeDependencies() { super.didChangeDependencies(); final ModalRoute<dynamic>? nextRoute = ModalRoute.of(context); if (nextRoute != _route) { _route?.unregisterPopEntry(this); _route = nextRoute; _route?.registerPopEntry(this); } } ``` ## Migration guide ### Migrating from `WillPopScope` to `PopScope` The direct replacement of the `WillPopScope` widget is the `PopScope` widget. In many cases, logic that was being run at the time of the back gesture in `onWillPop` can be done at build time and set to `canPop`. Code before migration: ```dart WillPopScope( onWillPop: () async { return _myCondition; }, child: ... ), ``` Code after migration: ```dart PopScope( canPop: _myCondition, child: ... ), ``` For cases where it's necessary to be notified that a pop was attempted, the `onPopInvoked` method can be used in a similar way to `onWillPop`. Keep in mind that while `onWillPop` was called before the pop was handled and had the ability to cancel it, `onPopInvoked` is called after the pop is finished being handled. Code before migration: ```dart WillPopScope( onWillPop: () async { _myHandleOnPopMethod(); return true; }, child: ... ), ``` Code after migration: ```dart PopScope( canPop: true, onPopInvoked: (bool didPop) { _myHandleOnPopMethod(); }, child: ... ), ``` ### Migrating from `WillPopScope` to `NavigatorPopHandler` for nested `Navigator`s A very common use case of `WillPopScope` was to properly handle back gestures when using nested `Navigator` widgets. It's possible to do this using `PopScope` as well, but there is now a wrapper widget that makes this even easier: `NavigatorPopHandler`. Code before migration: ```dart WillPopScope( onWillPop: () async => !(await _nestedNavigatorKey.currentState!.maybePop()), child: Navigator( key: _nestedNavigatorKey, … ), ) ``` Code after migration: ```dart NavigatorPopHandler( onPop: () => _nestedNavigatorKey.currentState!.pop(), child: Navigator( key: _nestedNavigatorKey, … ), ) ``` ### Migrating from `Form.onWillPop` to `Form.canPop` and `Form.onPopInvoked` Previously, `Form` used a `WillPopScope` instance under the hood and exposed its `onWillPop` method. This has been replaced with a `PopScope` that exposes its `canPop` and `onPopInvoked` methods. Migrating is identical to migrating from `WillPopScope` to `PopScope`, detailed above. ### Migrating from `Route.willPop` to `Route.popDisposition` `Route`'s `willPop` method returned a `Future<RoutePopDisposition>` to accommodate the fact that pops could be canceled. Now that that's no longer true, this logic has been simplified to a synchronous getter. Code before migration: ```dart if (await myRoute.willPop() == RoutePopDisposition.doNotPop) { ... } ``` Code after migration: ```dart if (myRoute.popDisposition == RoutePopDisposition.doNotPop) { ... } ``` ### Migrating from `ModalRoute.add/removeScopedWillPopCallback` to `ModalRoute.(un)registerPopEntry` Internally, `ModalRoute` kept track of the existence of `WillPopScope`s in its widget subtree by registering them with `addScopedWillPopCallback` and `removeScopedWillPopCallback`. Since `PopScope` replaces `WillPopScope`, these methods have been replaced by `registerPopEntry` and `unregisterPopEntry`, respectively. `PopEntry` is implemented by `PopScope` in order to expose only the minimal information necessary to `ModalRoute`. Anyone writing their own `PopScope` should implement `PopEntry` and register and unregister their widget with its enclosing `ModalRoute`. Code before migration: ```dart @override void didChangeDependencies() { super.didChangeDependencies(); if (widget.onWillPop != null) { _route?.removeScopedWillPopCallback(widget.onWillPop!); } _route = ModalRoute.of(context); if (widget.onWillPop != null) { _route?.addScopedWillPopCallback(widget.onWillPop!); } } ``` Code after migration: ```dart @override void didChangeDependencies() { super.didChangeDependencies(); _route?.unregisterPopEntry(this); _route = ModalRoute.of(context); _route?.registerPopEntry(this); } ``` ### Migrating from `ModalRoute.hasScopedWillPopCallback` to `ModalRoute.popDisposition` This method was previously used for a use-case very similar to Predictive Back but in the Cupertino library, where certain back transitions allowed canceling the navigation. The route transition was disabled when there was even the possibility of a `WillPopScope` widget canceling the pop. Now that the API requires this to be decided ahead of time, this no longer needs to be speculatively based on the existence of `PopScope` widgets. The definitive logic of whether a `ModalRoute` is having popping blocked by a `PopScope` widget is baked into `ModalRoute.popDisposition`. Code before migration: ```dart if (_route.hasScopedWillPopCallback) { // Disable predictive route transitions. } ``` Code after migration: ```dart if (_route.popDisposition == RoutePopDisposition.doNotPop) { // Disable predictive route transitions. } ``` ### Migrating a back confirmation dialog `WillPopScope` was sometimes used to show a confirmation dialog when a back gesture was received. This can still be done with `PopScope` in a similar pattern. Code before migration: ```dart WillPopScope( onWillPop: () async { final bool? shouldPop = await _showBackDialog(); return shouldPop ?? false; }, child: child, ) ``` Code after migration: ```dart return PopScope( canPop: false, onPopInvoked: (bool didPop) async { if (didPop) { return; } final NavigatorState navigator = Navigator.of(context); final bool? shouldPop = await _showBackDialog(); if (shouldPop ?? false) { navigator.pop(); } }, child: child, ) ``` ### Supporting predictive back 1. Run Android 33 or above. 1. Enable the feature flag for predictive back on the device under "Developer options". This will be unnecessary on future versions of Android. 1. Set `android:enableOnBackInvokedCallback="true"` in `android/app/src/main/AndroidManifest.xml`. If needed, refer to [Android's full guide]({{site.android-dev}}/guide/navigation/custom-back/predictive-back-gesture) for migrating Android apps to support predictive back. 1. Make sure you're using version `3.14.0-7.0.pre` of Flutter or greater. 1. Run the app and perform a back gesture (swipe from the left side of the screen). ## Timeline Landed in version: 3.14.0-7.0.pre<br> In stable release: 3.16 ## References API documentation: * [`PopScope`][] * [`NavigatorPopHandler`][] * [`PopScope`][] * [`NavigatorPopHandler`][] * [`PopEntry`][] * [`Form.canPop`][] * [`Form.onPopInvoked`][] * [`Route.popDisposition`][] * [`ModalRoute.registerPopEntry`][] * [`ModalRoute.unregisterPopEntry`][] Relevant issues: * [Issue 109513][] Relevant PRs: * [Predictive Back support for root routes][] * [Platform channel for predictive back][] [`PopScope`]: {{site.api}}/flutter/widgets/PopScope-class.html [`NavigatorPopHandler`]: {{site.api}}/flutter/widgets/NavigatorPopHandler-class.html [`PopEntry`]: {{site.api}}/flutter/widgets/PopEntry-class.html [`Form.canPop`]: {{site.api}}/flutter/widgets/Form/canPop.html [`Form.onPopInvoked`]: {{site.api}}/flutter/widgets/Form/onPopInvoked.html [`Route.popDisposition`]: {{site.api}}/flutter/widgets/Route/popDisposition.html [`ModalRoute.registerPopEntry`]: {{site.api}}/flutter/widgets/ModalRoute/registerPopEntry.html [`ModalRoute.unregisterPopEntry`]: {{site.api}}/flutter/widgets/ModalRoute/unregisterPopEntry.html [Issue 109513]: {{site.repo.flutter}}/issues/109513 [Predictive back support for root routes]: {{site.repo.flutter}}/pull/120385 [Platform channel for predictive back]: {{site.repo.engine}}/pull/39208
website/src/release/breaking-changes/android-predictive-back.md/0
{ "file_path": "website/src/release/breaking-changes/android-predictive-back.md", "repo_id": "website", "token_count": 3352 }
1,312
--- title: Bottom Navigation Title To Label description: > Deprecated BottomNavigationBarItem's title (a Widget) in favor of label (a String). --- ## Summary `BottomNavigationBarItem.title` gives a deprecation warning, or no longer exists when referenced in code. ## Context `BottomNavigationBarItem`s `title` parameter was deprecated in favor of `label`. This change was necessary to improve the user experience of `BottomNavigationBar`s when the text scale factor is increased. Items in a `BottomNavigationBar` now show tooltips on long press. Accomplishing this requires a `String` parameter on `BottomNavigationBarItem`s. ## Description of change The `BottomNavigationBarItem` class has a `title` parameter, which is a `Widget`. This made it impossible for the `BottomNavigationBar` to show `Tooltip` widgets, a change that was necessary to improve the accessibility experience. Now, instead of building the `BottomNavigationBarItem.title` widget, the BottomNavigationBar wraps the `BottomNavigationBarItem.label` in a Text widget and builds that. ## Migration guide Code before migration: ```dart BottomNavigationBarItem( icon: Icons.add, title: Text('add'), ) ``` Code after migration: ```dart BottomNavigationBarItem( icon: Icons.add, label: 'add', ) ``` ## Timeline Landed in version: 1.22.0 In stable release: 2.0.0 ## References API documentation: * [`BottomNavigationBarItem`][] Relevant PRs: * [PR 60655][]: Clean up hero controller scope * [PR 59127][]: Update BottomNavigationBar to show tooltips on long press. Breaking change proposal: * [Breaking Change: Bottom Navigation Item Title][] [`BottomNavigationBarItem`]: {{site.api}}/flutter/widgets/BottomNavigationBarItem-class.html [Breaking Change: Bottom Navigation Item Title]: /go/bottom-navigation-bar-title-deprecation [PR 59127]: {{site.repo.flutter}}/pull/59127 [PR 60655]: {{site.repo.flutter}}/pull/60655
website/src/release/breaking-changes/bottom-navigation-title-to-label.md/0
{ "file_path": "website/src/release/breaking-changes/bottom-navigation-title-to-label.md", "repo_id": "website", "token_count": 571 }
1,313
--- title: Dialogs' Default BorderRadius description: The default BorderRadius of Dialog widgets is changing. --- ## Summary Instances of `Dialog`, as well as `SimpleDialog`, `AlertDialog`, and `showTimePicker`, now have a default shape of a `RoundedRectangleBorder` with a `BorderRadius` of 4.0 pixels. This matches the current specifications of Material Design. Prior to this change, the default behavior for `Dialog.shape`'s `BorderRadius` was 2.0 pixels. ## Context `Dialog`s and their associated subclasses (`SimpleDialog`, `AlertDialog`, and `showTimePicker`), appears slightly different as the border radius is larger. If you have master golden file images that have the prior rendering of the `Dialog` with a 2.0 pixel border radius, your widget tests will fail. These golden file images can be updated to reflect the new rendering, or you can update your code to maintain the original behavior. The `showDatePicker` dialog already matched this specification and is unaffected by this change. ## Migration guide If you prefer to maintain the old shape, you can use the shape property of your `Dialog` to specify the original 2 pixel radius. Setting the Dialog shape to the original radius: ```dart import 'package:flutter/material.dart'; void main() => runApp(Foo()); class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton(onPressed: () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( content: Text('Alert!'), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(2))), ); }, ); }), ), ); } } ``` If you prefer the new behavior and have failing golden file tests, you can update your master golden files using this command: ```terminal flutter test --update-goldens ``` ## Timeline Landed in version: 1.20.0-0.0.pre<br> In stable release: 1.20 ## References API documentation: * [`Dialog`][] * [`SimpleDialog`][] * [`AlertDialog`][] * [`showTimePicker`][] * [`showDatePicker`][] Relevant PR: * [PR 58829: Matching Material Spec for Dialog shape][] [`Dialog`]: {{site.api}}/flutter/material/Dialog-class.html [`SimpleDialog`]: {{site.api}}/flutter/material/SimpleDialog-class.html [`AlertDialog`]: {{site.api}}/flutter/material/AlertDialog-class.html [`showTimePicker`]: {{site.api}}/flutter/material/showTimePicker.html [`showDatePicker`]: {{site.api}}/flutter/material/showDatePicker.html [PR 58829: Matching Material Spec for Dialog shape]: {{site.repo.flutter}}/pull/58829
website/src/release/breaking-changes/dialog-border-radius.md/0
{ "file_path": "website/src/release/breaking-changes/dialog-border-radius.md", "repo_id": "website", "token_count": 940 }
1,314
--- title: ImageCache and ImageProvider changes description: > ImageCache requires implementers to override containsKey, and ImageProvider has marked resolve as @nonVirtual. --- ## Summary `ImageCache` now has a method called `containsKey`. `ImageProvider` subclasses should not override `resolve`, but instead should implement new methods on `ImageProvider`. These changes were submitted as a single commit to the framework. ## Description of change The sections below describe the changes to `containsKey` and `ImageProvider`. ### containsKey change Clients of the `ImageCache`, such as a custom `ImageProvider`, may want to know if the cache is already tracking an image. Adding the `containsKey` method allows callers to discover this without calling a method like `putIfAbsent`, which can trigger an undesired call to `ImageProvider.load`. The default implementation checks both pending and cached image buckets. ```dart bool containsKey(Object key) { return _pendingImages[key] != null || _cache[key] != null; } ``` ### ImageProvider changes The `ImageProvider.resolve` method does some complicated error handling work that should not normally be overridden. It also previously did work to load the image into the image cache, by way of `ImageProvider.obtainKey` and `ImageProvider.load`. Subclasses had no opportunity to override this behavior without overriding `resolve`, and the ability to compose `ImageProvider`s is limited if multiple `ImageProvider`s expect to override `resolve`. To solve this issue, `resolve` is now marked as non-virtual, and two new protected methods have been added: `createStream()` and `resolveStreamForKey()`. These methods allow subclasses to control most of the behavior of `resolve`, without having to duplicate all the error handling work. It also allows subclasses that compose `ImageProvider`s to be more confident that there is only one public entrypoint to the various chained providers. ## Migration guide ### ImageCache change Before migration, the code would not have an override of `containsKey`. Code after migration: ```dart class MyImageCache implements ImageCache { @override bool containsKey(Object key) { // Check if your custom cache is tracking this key. } ... } ``` ### ImageProvider change Code before the migration: ```dart class MyImageProvider extends ImageProvider<Object> { @override ImageStream resolve(ImageConfiguration configuration) { // create stream // set up error handling // interact with ImageCache // call obtainKey/load, etc. } ... } ``` Code after the migration: ```dart class MyImageProvider extends ImageProvider<Object> { @override ImageStream createStream(ImageConfiguration configuration) { // Return stream, or use super.createStream(), // which returns a new ImageStream. } @override void resolveStreamForKey( ImageConfiguration configuration, ImageStream stream, Object key, ImageErrorListener handleError, ) { // Interact with the cache, use the key, potentially call `load`, // and report any errors back through `handleError`. } ... } ``` ## Timeline Landed in version: 1.16.3<br> In stable release: 1.17 ## References API documentation: * [`ImageCache`][] * [`ImageProvider`][] * [`ScrollAwareImageProvider`][] Relevant issues: * [Issue #32143][] * [Issue #44510][] * [Issue #48305][] * [Issue #48775][] Relevant PRs: * [Defer image decoding when scrolling fast #49389][] [`ImageCache`]: {{site.api}}/flutter/painting/ImageCache-class.html [`ImageProvider`]: {{site.api}}/flutter/painting/ImageProvider-class.html [`ScrollAwareImageProvider`]: {{site.api}}/flutter/widgets/ScrollAwareImageProvider-class.html [Issue #32143]: {{site.repo.flutter}}/issues/32143 [Issue #44510]: {{site.repo.flutter}}/issues/44510 [Issue #48305]: {{site.repo.flutter}}/issues/48305 [Issue #48775]: {{site.repo.flutter}}/issues/48775 [Defer image decoding when scrolling fast #49389]: {{site.repo.flutter}}/pull/49389
website/src/release/breaking-changes/image-cache-and-provider.md/0
{ "file_path": "website/src/release/breaking-changes/image-cache-and-provider.md", "repo_id": "website", "token_count": 1165 }
1,315
--- title: MouseTracker moved to rendering description: MouseTracker and related symbols moved to the rendering package. --- ## Summary [`MouseTracker`][] and related symbols are moved from the `gestures` package, resulting in error messages such as undefined classes or methods. Import them from `rendering` package instead. ## Context Prior to this change [`MouseTracker`][] was part of the `gestures` package. This brought troubles when we found out that code related to [`MouseTracker`][] often wanted to import from the `rendering` package. Since [`MouseTracker`][] turned out to be more connected to `rendering` than `gestures`, we have moved it and its related code to `rendering`. ## Description of change The file `mouse_tracking.dart` has been moved from the `gestures` package to `rendering`. All symbols in the said file have been moved without keeping backward compatibility. ## Migration guide If you see error of "Undefined class" or "Undefined name" of the following symbols: * [`MouseDetectorAnnotationFinder`][] * [`MouseTracker`][] * [`MouseTrackerAnnotation`][] * [`PointerEnterEventListener`][] * [`PointerExitEventListener`][] * [`PointerHoverEventListener`][] You should add the following import: ```dart import 'package:flutter/rendering.dart'; ``` ## Timeline Landed in version: 1.16.3<br> In stable release: 1.17 ## References API documentation: * [`MouseDetectorAnnotationFinder`][] * [`MouseTracker`][] * [`MouseTrackerAnnotation`][] * [`PointerEnterEventListener`][] * [`PointerExitEventListener`][] * [`PointerHoverEventListener`][] Relevant issues: * [Transform mouse events to the local coordinate system][] * [Move annotations to a separate tree][] Relevant PR: * [Move mouse_tracking.dart to rendering][] [Move annotations to a separate tree]: {{site.repo.flutter}}/issues/49568 [Move mouse_tracking.dart to rendering]: {{site.repo.flutter}}/pull/52781 [Transform mouse events to the local coordinate system]: {{site.repo.flutter}}/issues/33675 [`MouseDetectorAnnotationFinder`]: {{site.api}}/flutter/gestures/MouseDetectorAnnotationFinder.html [`MouseTracker`]: {{site.api}}/flutter/gestures/MouseTracker-class.html [`MouseTrackerAnnotation`]: {{site.api}}/flutter/gestures/MouseTrackerAnnotation-class.html [`PointerEnterEventListener`]: {{site.api}}/flutter/gestures/PointerEnterEventListener.html [`PointerExitEventListener`]: {{site.api}}/flutter/gestures/PointerExitEventListener.html [`PointerHoverEventListener`]: {{site.api}}/flutter/gestures/PointerHoverEventListener.html
website/src/release/breaking-changes/mouse-tracker-moved-to-rendering.md/0
{ "file_path": "website/src/release/breaking-changes/mouse-tracker-moved-to-rendering.md", "repo_id": "website", "token_count": 777 }
1,316
--- title: The RenderEditable needs to be laid out before hit testing description: > The hit testing of RenderEditable requires additional information that is only available after the layout. --- ## Summary Instances of `RenderEditable` must be laid out before processing hit testing. Trying to hit-test a `RenderEditable` object before layout results in an assertion such as the following: ```nocode Failed assertion: line 123 pos 45: '!debugNeedsLayout': is not true. ``` ## Context To support gesture recognizers in selectable text, the `RenderEditable` requires the layout information for its text spans to determine which text span receives the pointer event. (Before this change, `RenderEditable` objects didn't take their text into account when evaluating hit tests.) To implement this, layout was made a prerequisite for performing hit testing on a `RenderEditable` object. In practice, this is rarely an issue. The widget library ensures that layout is performed before any hit test on all render objects. This problem is only likely to be seen in code that directly interacts with render objects, for example in tests of custom render objects. ## Migration guide If you see the `'!debugNeedsLayout': is not true` assertion error while hit testing the `RenderEditable`, lay out the `RenderEditable` before doing so. Code before migration: ```dart import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; void main() { test('attach and detach correctly handle gesture', () { final RenderEditable editable = RenderEditable( textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: FakeEditableTextState(), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); final PipelineOwner owner = PipelineOwner(onNeedVisualUpdate: () {}); editable.attach(owner); // This throws an assertion error because // the RenderEditable hasn't been laid out. editable.handleEvent(const PointerDownEvent(), BoxHitTestEntry(editable, const Offset(10, 10))); editable.detach(); }); } class FakeEditableTextState extends TextSelectionDelegate { @override TextEditingValue textEditingValue; @override void hideToolbar() {} @override void bringIntoView(TextPosition position) {} } ``` Code after migration: ```dart import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; void main() { test('attach and detach correctly handle gesture', () { final RenderEditable editable = RenderEditable( textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: FakeEditableTextState(), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); // Lay out the RenderEditable first. editable.layout(BoxConstraints.loose(const Size(1000.0, 1000.0))); final PipelineOwner owner = PipelineOwner(onNeedVisualUpdate: () {}); editable.attach(owner); editable.handleEvent(const PointerDownEvent(), BoxHitTestEntry(editable, const Offset(10, 10))); editable.detach(); }); } class FakeEditableTextState extends TextSelectionDelegate { @override TextEditingValue textEditingValue; @override void hideToolbar() {} @override void bringIntoView(TextPosition position) {} } ``` ## Timeline Landed in version: 1.18.0<br> In stable release: 1.20 ## References API documentation: * [`RenderEditable`][] Relevant issue: * [Issue 43494][]: SelectableText.rich used along with TapGestureRecognizer isn't working Relevant PR: * [PR 54479: Enable gesture recognizer in selectable rich text][] [Issue 43494]: {{site.repo.flutter}}/issues/43494 [`RenderEditable`]: {{site.api}}/flutter/rendering/RenderEditable-class.html [PR 54479: Enable gesture recognizer in selectable rich text]: {{site.repo.flutter}}/pull/54479
website/src/release/breaking-changes/rendereditable-layout-before-hit-test.md/0
{ "file_path": "website/src/release/breaking-changes/rendereditable-layout-before-hit-test.md", "repo_id": "website", "token_count": 1235 }
1,317
--- title: TestTextInput state reset description: TestTextInput state is now reset between tests. --- ## Summary The state of a `TestTextInput` instance, a stub for the system's onscreen keyboard, is now reset between tests. ## Context The Flutter test framework uses a class called `TestTextInput` to track and manipulate editing state in a widgets test. Individual tests can make calls that modify the internal state of this object, sometimes indirectly (such as by setting their own handlers on `SystemChannels.textInput`). Subsequent tests might then check the state of `WidgetTester.testTextInput` and get unexpected values. ## Description of change The state of `WidgetTester.testTextInput` is now reset before running a `testWidgets` test. ## Migration guide Tests that relied on dirty state from a previously run test must be updated. For example, the following test, from `packages/flutter/test/material/text_field_test.dart` in the `'Controller can update server'` test, previously passed because of a combination of dirty state from previous tests and a failure to actually set state in cases where it should have been set. Code before migration: In a `widgetsTest`, before actually changing text on a text editing widget, this call might have succeeded: ```dart expect(tester.testTextInput.editingState['text'], isEmpty); ``` Code after migration: Either remove the call entirely, or consider using the following to assert that the state hasn't been modified yet: ```dart expect(tester.testTextInput.editingState, isNull); ``` ## Timeline Landed in version: 1.16.3<br> In stable release: 1.17 ## References API documentation: * [`TestTextInput`][] * [`WidgetTester`][] Relevant issue: * [Randomize test order to avoid global state][] Relevant PR: * [Reset state between tests][] [Randomize test order to avoid global state]: {{site.repo.flutter}}/issues/47233 [Reset state between tests]: {{site.repo.flutter}}/pull/47464 [`TestTextInput`]: {{site.api}}/flutter/flutter_test/TestTextInput-class.html [`WidgetTester`]: {{site.api}}/flutter/flutter_test/WidgetTester-class.html
website/src/release/breaking-changes/test-text-input.md/0
{ "file_path": "website/src/release/breaking-changes/test-text-input.md", "repo_id": "website", "token_count": 611 }
1,318
--- title: Migrate a Windows project to set version information description: How to update a Windows project to set version information --- Flutter 3.3 added support for setting the Windows app's version from the `pubspec.yaml` file or through the `--build-name` and `--build-number` build arguments. For more information, refer to the [Build and release a Windows app][] documentation. Projects created before Flutter version 3.3 need to be migrated to support versioning. ## Migration steps Your project can be updated using these steps: 1. Verify you are on Flutter version 3.3 or newer using `flutter --version` 2. If needed, use `flutter upgrade` to update to the latest version of the Flutter SDK 3. Backup your project, possibly using git or some other version control system 4. Delete the `windows/runner/CMakeLists.txt` and `windows/runner/Runner.rc` files 5. Run `flutter create --platforms=windows .` 6. Review the changes to your `windows/runner/CMakeLists.txt` and `windows/runner/Runner.rc` files 7. Verify your app builds using `flutter build windows` {{site.alert.note}} Follow the [run loop migration guide][] if the build fails with the following error message: ``` flutter_window.obj : error LNK2019: unresolved external symbol "public: void __cdecl RunLoop::RegisterFlutterInstance(class flutter::FlutterEngine *)" (?RegisterFlutterInstance@RunLoop@@QEAAXPEAVFlutterEngine@flutter@@@Z) referenced in function "protected: virtual bool __cdecl FlutterWindow::OnCreate(void)" (?OnCreate@FlutterWindow@@MEAA_NXZ) ``` {{site.alert.end}} ## Example [PR 721][] shows the migration work for the [Flutter Gallery][] app. [Build and release a Windows app]: /deployment/windows#updating-the-apps-version-number [run loop migration guide]: /release/breaking-changes/windows-run-loop [PR 721]: {{site.repo.gallery-archive}}/pull/721/files [Flutter Gallery]: {{site.gallery-archive}}
website/src/release/breaking-changes/windows-version-information.md/0
{ "file_path": "website/src/release/breaking-changes/windows-version-information.md", "repo_id": "website", "token_count": 545 }
1,319
--- title: Flutter 1.5.4 release notes short-title: 1.5.4 release notes description: Release notes for Flutter 1.5.4. --- In addition to continuing to focus on quality and stability since the 1.2 release, the Flutter 1.5.4 stable release adds a set of new features as we approach the Google I/O conference. Further, [Apple has a deadline for building against the 12.1 version of their iOS SDK](https://developer.apple.com/news/?id=03202019a), which we now do in this update. You can meet Apple's requirements simply by pulling down the 1.5.4 stable release, building and updating your Flutter app in the Apple Store. Also, this build sees fixes for the two regressions we saw in Flutter 1.2: * [#28640](https://github.com/flutter/flutter/issues/28640) NoSuchMethodError: **android.view.MotionEvent.isFromSource was closed and fixed in all versions after 1.3.7 * [#28484](https://github.com/flutter/flutter/issues/28484) Widget rendering strange since Flutter update:** a change was made fixes this regression in 1.4.0 Finally, for details about other fixes and new features, read on. ## Breaking Changes Our recent survey showed that Flutter developers prefer a breaking change if it means that it improves the API and behavior of Flutter. Of course, we still make breaking changes sparingly. The following are the list of breaking changes in this release along with links to a full description of each change and how to handle it in your Flutter code. * [flutter#26261](https://github.com/flutter/flutter/issues/26261): CupertinoTextField's cursorColor default now matches the app's theme ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/uJFi5sENr1g)) * [flutter#26026](https://github.com/flutter/flutter/issues/26261): Need to manually trigger selection toolbars when using raw EditableText ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/uJFi5sENr1g)) * [flutter#23148](https://github.com/flutter/flutter/issues/26261): Proposing a fix to unify Android and iOS response in the Firebase Messagng Plugin ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/v4dt7Zc-NGg)) * [flutter#28014](https://github.com/flutter/flutter/issues/26261): Converting PointerEvent to Diagnosticable ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/ZPPRKV642Uk)) * [flutter#20183](https://github.com/flutter/flutter/issues/26261): CupertinoTextField: Merge provided TextStyle with Theme's TextStyle ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/3OV8J3GhO6U)) * [flutter#20693](https://github.com/flutter/flutter/issues/26261): LongPressGestureRecognizer moving after long press no longer discards up event ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/kWT0J8Ii5Rw)) * [flutter#20693](https://github.com/flutter/flutter/issues/26261): The GestureRecognizerState enum has a new 'accepted' value ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/YXNZ4OFL8Uo)) * [flutter#18314](https://github.com/flutter/flutter/issues/26261), [flutter#22830](https://github.com/flutter/flutter/issues/26261), [flutter#23424](https://github.com/flutter/flutter/issues/26261): Drag moveBy calls are broken in two and the default DragStartBehavior in all widgets with drag recognizers is changed to DragStartBehavior.start ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/iTZt49dP_pU)) * [flutter#27891](https://github.com/flutter/flutter/issues/26261): Composite layers for physical shapes on all platforms ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/8bAn-BPQPE8)) * [flutter#19418](https://github.com/flutter/flutter/issues/26261): Adding onPlatformViewCreated to AndroidViewController ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/LoAfcK5IJ9A)) * [flutter#29070](https://github.com/flutter/flutter/issues/26261): BackdropFilter will fill its parent/ancestor clip ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/AC4NDVh1h5k)) * [flutter#29816](https://github.com/flutter/flutter/issues/26261): FontWeight.lerp to return null if args are null ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/0uS_Hzq894I)) * [flutter#29696](https://github.com/flutter/flutter/issues/26261): Proposal to rename PointerEnterEvent and PointerExitEvent fromHoverEvent to fromMouseEvent ([Announcement & Mitigation](https://groups.google.com/forum/#!topic/flutter-announce/ECoJc9LOs2M)) * [flutter#28602](https://github.com/flutter/flutter/pull/28602): Allow PointerEnterEvent and PointerExitEvents to be created from any PointerEvent * [flutter#28953](https://github.com/flutter/flutter/pull/28953): Include platformViewId in semantics tree * [flutter#27612](https://github.com/flutter/flutter/pull/27612): Force line height in TextFields with strut * [flutter#30991](https://github.com/flutter/flutter/pull/30991): Use full height of the glyph for caret height on Android * [flutter#30414](https://github.com/flutter/flutter/pull/30414): Remove pressure customization from some pointer events * [engine#8274](https://github.com/flutter/engine/pull/8274): [ui] Add null check in FontWeight.lerp ## Severe Performance and Crash Changes In this release, we fixed several severe performance and crash issues. * [flutter#30990](https://github.com/flutter/flutter/pull/30990): Allow profile widget builds in profile mode * [flutter#30985](https://github.com/flutter/flutter/pull/30985): Add rrect contains microbenchmark * [flutter#28651](https://github.com/flutter/flutter/pull/28651): Cannot execute operation because FlutterJNI is not attached to native. ## iOS Changes Supporting iOS is just as important to the Flutter team as support Android, which you can see in the huge volume of changes we've made in this release to make the iOS experience even better. * [flutter#29200](https://github.com/flutter/flutter/pull/29200): Cupertino localization step 1: add an English arb file * [flutter#29821](https://github.com/flutter/flutter/pull/29821): Cupertino localization step 1.5: fix a resource mismatch in cupertino_en.arb * [flutter#30160](https://github.com/flutter/flutter/pull/30160): Cupertino localization 1.9: add needed singular resource for cupertino_en.arb * [flutter#29644](https://github.com/flutter/flutter/pull/29644): Cupertino localization step 3: in-place move some material tools around to make room for cupertino * [flutter#29650](https://github.com/flutter/flutter/pull/29650): Cupertino localization step 4: let generated date localization combine material and cupertino locales * [flutter#29708](https://github.com/flutter/flutter/pull/29708) Cupertino localization step 5: add french arb as translated example * [flutter#29767](https://github.com/flutter/flutter/pull/29767): Cupertino localization step 6: add a GlobalCupertinoLocalizations base class with date time formatting * [flutter#30527](https://github.com/flutter/flutter/pull/30527): Cupertino localization step 11: add more translation clarifications in the instructions * [flutter#28629](https://github.com/flutter/flutter/pull/28629): Make sure everything in the Cupertino page transition can be linear when back swiping * [flutter#28001](https://github.com/flutter/flutter/pull/28001): CupertinoTextField: added ability to change placeholder color * [flutter#29304](https://github.com/flutter/flutter/pull/29304): Include platformViewId in semantics tree for iOS * [flutter#29946](https://github.com/flutter/flutter/pull/29946): Let CupertinoPageScaffold have tap status bar to scroll to top * [flutter#29474](https://github.com/flutter/flutter/pull/29474): Let CupertinoTextField's clear button also call onChanged * [flutter#29008](https://github.com/flutter/flutter/pull/29008): Update CupertinoTextField * [flutter#29630](https://github.com/flutter/flutter/pull/29630): Add heart shapes to CupertinoIcons * [flutter#28597](https://github.com/flutter/flutter/pull/28597): Adjust remaining Cupertino route animations to match native * [flutter#29407](https://github.com/flutter/flutter/pull/29407): [cupertino_icons] Add circle and circle_filled, for radio buttons. * [flutter#29024](https://github.com/flutter/flutter/pull/29024): Fix CupertinoTabView tree re-shape on view inset change * [flutter#28478](https://github.com/flutter/flutter/pull/28478): Support iOS devices reporting pressure data of 0 * [flutter#29987](https://github.com/flutter/flutter/pull/29987): update CupertinoSwitch documentation * [flutter#29943](https://github.com/flutter/flutter/pull/29943): Remove unwanted gap between navigation bar and safe area's child * [flutter#28855](https://github.com/flutter/flutter/pull/28855): Move material iOS back swipe test to material * [flutter#28756](https://github.com/flutter/flutter/pull/28756): Handle Cupertino back gesture interrupted by Navigator push * [flutter#31088](https://github.com/flutter/flutter/pull/31088): Text field scroll physics * [flutter#30946](https://github.com/flutter/flutter/pull/30946): Add some more cupertino icons * [flutter#30521](https://github.com/flutter/flutter/pull/30521): Provide a default IconTheme in CupertinoTheme * [flutter#30475](https://github.com/flutter/flutter/pull/30475): Trackpad mode crash fix ## Material Changes Of course, Material continues to be a priority for the Flutter team as well. * [flutter#28290](https://github.com/flutter/flutter/pull/28290): [Material] Create a FloatingActionButton ThemeData and honor it within the FloatingActionButton ([#28735](https://github.com/flutter/flutter/pull/28735)) * [flutter#29980](https://github.com/flutter/flutter/pull/29980): Fix issue with account drawer header arrow rotating when setState is called * [flutter#29563](https://github.com/flutter/flutter/pull/29563): Avoid flickering while dragging to select text * [flutter#29138](https://github.com/flutter/flutter/pull/29138): Update DropdownButton underline to be customizable * [flutter#29572](https://github.com/flutter/flutter/pull/29572): DropdownButton Icon customizability * [flutter#29183](https://github.com/flutter/flutter/pull/29183): Implement labelPadding configuration in TabBarTheme * [flutter#21834](https://github.com/flutter/flutter/pull/21834): Add shapeBorder option on App Bar * [flutter#28163](https://github.com/flutter/flutter/pull/28163): [Material] Add ability to set shadow color and selected shadow color for chips and for chip themes * [flutter#27711](https://github.com/flutter/flutter/pull/27711): Make extended FAB's icon optional * [flutter#28159](https://github.com/flutter/flutter/pull/28159): [Material] Expand BottomNavigationBar API (reprise) * [flutter#27973](https://github.com/flutter/flutter/pull/27973): Add extendBody parameter to Scaffold, body MediaQuery reflects BAB height * [flutter#30390](https://github.com/flutter/flutter/pull/30390): [Material] Update slider and slider theme with new sizes, shapes, and color mappings * [flutter#29390](https://github.com/flutter/flutter/pull/29390): Make expansion panel optionally toggle its state by tapping its header. * [flutter#30754](https://github.com/flutter/flutter/pull/30754): [Material] Fix showDialog crasher caused by old contexts * [flutter#30525](https://github.com/flutter/flutter/pull/30525): Fix cursor outside of input width * [flutter#30805](https://github.com/flutter/flutter/pull/30805): Update ExpansionPanelList Samples with Scaffold Template * [flutter#30537](https://github.com/flutter/flutter/pull/30537): Embedded images and added variations to ListTile sample code * [flutter#30455](https://github.com/flutter/flutter/pull/30455): Prevent vertical scroll in shrine by ensuring card size fits the screen * [flutter#29413](https://github.com/flutter/flutter/pull/29413): Fix MaterialApp's _navigatorObserver when only builder used ## Desktop Changes Flutter has been making progress on expanding support for desktop-class input mechanisms with keyboard mappings, text selection, mouse wheels and hover along with the beginnings of desktop support in our tooling. * [flutter#29993](https://github.com/flutter/flutter/pull/29993): Adds the keyboard mapping for Linux * [flutter#29769](https://github.com/flutter/flutter/pull/29769): Add support for text selection via mouse to Cupertino text fields * [flutter#22762](https://github.com/flutter/flutter/pull/22762): Add support for scrollwheels * [flutter#28900](https://github.com/flutter/flutter/pull/28900): Add key support to cupertino button * [flutter#28290](https://github.com/flutter/flutter/pull/28290): Text selection via mouse * [flutter#28602](https://github.com/flutter/flutter/pull/28602): Allow PointerEnterEvent and PointerExitEvents to be created from any PointerEvent * [flutter#30829](https://github.com/flutter/flutter/pull/30829): Keep hover annotation layers in sync with the mouse detector. * [flutter#30648](https://github.com/flutter/flutter/pull/30648): Allow downloading of desktop embedding artifacts * [flutter#31283](https://github.com/flutter/flutter/pull/31283): Add desktop workflows to doctor * [flutter#31229](https://github.com/flutter/flutter/pull/31229): Add flutter run support for linux and windows * [flutter#31277](https://github.com/flutter/flutter/pull/31277): pass track widget creation flag through to build script * [flutter#31218](https://github.com/flutter/flutter/pull/31218): Add run capability for macOS target * [flutter#31205](https://github.com/flutter/flutter/pull/31205): Add desktop projects and build commands (experimental) * [flutter#30670](https://github.com/flutter/flutter/issues/30670): Implement StandardMethodCodec for C++ shells ## Framework Changes In addition to platform specifics, we continue to push on the core of the Flutter framework. * [engine#8402](https://github.com/flutter/engine/pull/8402): Enable shutting down all root isolates in a VM. * [flutter#31210](https://github.com/flutter/flutter/pull/31210): Use full height of the glyph for caret height on Android v2 * [flutter#30422](https://github.com/flutter/flutter/pull/30422): Commit a navigator.pop as soon as the back swipe is lifted * [flutter#30792](https://github.com/flutter/flutter/pull/30792): Rename Border.uniform() -> Border.fromSide() * [flutter#31159](https://github.com/flutter/flutter/pull/31159): Revert "Use full height of the glyph for caret height on Android" * [flutter#30932](https://github.com/flutter/flutter/pull/30932): 2d transforms UX improvements * [flutter#30898](https://github.com/flutter/flutter/pull/30898): Check that ErrorWidget.builder is not modified after test * [flutter#30809](https://github.com/flutter/flutter/pull/30809): Fix issue 23527: Exception: RenderViewport exceeded its maximum numb… * [flutter#30880](https://github.com/flutter/flutter/pull/30880): Let sliver.dart _createErrorWidget work with other Widgets * [flutter#30876](https://github.com/flutter/flutter/pull/30876): Simplify toImage future handling * [flutter#30470](https://github.com/flutter/flutter/pull/30470): Fixed Table flex column layout error #30437 * [flutter#30215](https://github.com/flutter/flutter/pull/30215): Check for invalid elevations * [flutter#30667](https://github.com/flutter/flutter/pull/30667): Fix additional @mustCallSuper indirect overrides and mixins * [flutter#30814](https://github.com/flutter/flutter/pull/30814): Fix StatefulWidget and StatelessWidget Sample Documentation * [flutter#30760](https://github.com/flutter/flutter/pull/30760): fix cast NPE in invokeListMethod and invokeMapMethod * [flutter#30640](https://github.com/flutter/flutter/pull/30640): Add const Border.uniformSide() * [flutter#30644](https://github.com/flutter/flutter/pull/30644): Make FormField._validate() return void * [flutter#30645](https://github.com/flutter/flutter/pull/30645): Add docs to FormFieldValidator * [flutter#30563](https://github.com/flutter/flutter/pull/30563): Fixed a typo in the Expanded API doc * [flutter#30513](https://github.com/flutter/flutter/pull/30513): Fix issue 21640: Assertion Error : '_listenerAttached': is not true * [flutter#30305](https://github.com/flutter/flutter/pull/30305): shorter nullable list duplications * [flutter#30468](https://github.com/flutter/flutter/pull/30468): Embedding diagram for BottomNavigationBar. ## Plugin Changes In this release, we also have a number of changes in the Flutter plugins, including camera, Google Maps, the Web View, the image picker, the Firebase plugins and, now for use in your apps, [the In-App Purchase plugin beta](https://pub.dartlang.org/packages/in_app_purchase). * [plugins#1477](https://github.com/flutter/plugins/pull/1477): [camera] Remove activity lifecycle * [plugins#1022](https://github.com/flutter/plugins/pull/1022): [camera] Add serial dispatch_queue for camera plugin to avoid blocking the UI * [plugins#1331](https://github.com/flutter/plugins/pull/1331): [connectivity] Enable fetching current Wi-Fi network's BSSID * [plugins#1455](https://github.com/flutter/plugins/pull/1455): [connectivity]Added integration test. * [plugins#1377](https://github.com/flutter/plugins/pull/1377): [firebase_admob] Update documentation to add iOS Admob ID & add iOS Admob ID in example project * [plugins#1492](https://github.com/flutter/plugins/pull/1492): [firebase_analytics] Initial integration test * [plugins#896](https://github.com/flutter/plugins/pull/896): [firebase-analytics] Enable setAnalyticsCollectionEnabled support for iOS * [plugins#1159](https://github.com/flutter/plugins/pull/1159): [firebase_auth] Enable passwordless sign in * [plugins#1487](https://github.com/flutter/plugins/pull/1487): [firebase_auth] Migrate FlutterAuthPlugin from deprecated APIs * [plugins#1443](https://github.com/flutter/plugins/pull/1443): [firebase_core] Use Gradle BoM with firebase_core * [plugins#1427](https://github.com/flutter/plugins/pull/1427): [firebase_crashlytics] Do not break debug log formatting. * [plugins#1437](https://github.com/flutter/plugins/pull/1437): [firebase_crashlytics] Fix to Initialize Fabric * [plugins#1096](https://github.com/flutter/plugins/pull/1096) :[firebase_database]Return error message from DatabaseError#toString() * [plugins#1532](https://github.com/flutter/plugins/pull/1532): [firebase_messaging] remove obsolete docs instruction * [plugins#1405](https://github.com/flutter/plugins/pull/1405): [firebase_messaging] Additional step for iOS * [plugins#1353](https://github.com/flutter/plugins/pull/1353): [firebase_messaging] Update example * [plugins#1223](https://github.com/flutter/plugins/pull/1223): [firebase_ml_vision] Fix crash when scanning URL QR-code on iOS * [plugins#1514](https://github.com/flutter/plugins/pull/1514): [firebase_remote_config] Initial integration tests * [plugins#815](https://github.com/flutter/plugins/pull/815): [google_maps_flutter] adds support for custom icon from a byte array (PNG) * [plugins#1229](https://github.com/flutter/plugins/pull/1229): [google_maps_flutter] Marker APIs are now widget based (Android) * [plugins#1421](https://github.com/flutter/plugins/pull/1421): [in_app_purchase]make payment unified APIs * [plugins#1380](https://github.com/flutter/plugins/pull/1380): [in_app_purchase]load purchase * [flutter#26329](https://github.com/flutter/flutter/issues/26329): IAP: Purchase an auto-renewing subscription * [flutter#26331](https://github.com/flutter/flutter/issues/26331): IAP: Purchase a non-renewing subscription * [flutter#26326](https://github.com/flutter/flutter/issues/26326): IAP: Load previous purchases * [plugins#1249](https://github.com/flutter/plugins/pull/1249): [in_app_purchase] payment queue dart ios * [flutter#26327](https://github.com/flutter/flutter/pull/26327): IAP: Purchase an unlock * [flutter#26328](https://github.com/flutter/flutter/pull/26328): IAP: Purchase a consumable * [flutter#29837](https://github.com/flutter/flutter/issues/29837): Image_picker flickers when barcode_scan and image_picker are used together * [flutter#17950](https://github.com/flutter/flutter/issues/17950): Image_picker plugin fails, if Flutter activity is killed while native one is shown * [flutter#18700](https://github.com/flutter/flutter/issues/18700): [image_picker] Crash on Galaxy S5 and Note 4 when attempting to use the camera * [plugins#1372](https://github.com/flutter/plugins/pull/1372): [image_picker] fix "Cancel button not visible in gallery, if camera was accessed first" * [plugins#1471](https://github.com/flutter/plugins/pull/1471): [image_picker] Fix invalid path being returned from Google Photos * [flutter#29422](https://github.com/flutter/flutter/issues/29422): image_picker error:Permission Denial * [plugins#1237](https://github.com/flutter/plugins/pull/1237): [share] Changed compileSdkVersion of share plugin to 28 * [plugins#1373](https://github.com/flutter/plugins/pull/1373): [shared_preferences] Add contains method * [plugins#1470](https://github.com/flutter/plugins/pull/1470): [video_player] Android: Added missing event.put("event", "completed"); * [flutter#25329](https://github.com/flutter/flutter/pull/25329): [WebView] Allow the webview to take control when a URL is about to be loaded ## Tool Changes Last but certainly not least, we made a number of tooling changes in the core Flutter repos to improve the developer experience, particularly when it comes to improving hot reload performance (and you thought it was fast before!). * [flutter#29693](https://github.com/flutter/flutter/pull/29693): Use source list from the compiler to track invalidated files for hot reload. * [flutter#28152](https://github.com/flutter/flutter/pull/28152): Improve hot reload performance * [flutter#29494](https://github.com/flutter/flutter/pull/29494): initial work on coverage generating script for tool * [flutter#31171](https://github.com/flutter/flutter/pull/31171): Allow disabling all fingerprint caches via environment variable * [flutter#31073](https://github.com/flutter/flutter/pull/31073): Fuchsia step 1: add SDK version file and artifact download * [flutter#31064](https://github.com/flutter/flutter/pull/31064): Add sorting to flutter version command * [flutter#31063](https://github.com/flutter/flutter/pull/31063): Download and handle product version of flutter patched sdk * [flutter#31074](https://github.com/flutter/flutter/pull/31074): make flutterProject option of CoverageCollector optional * [flutter#30818](https://github.com/flutter/flutter/pull/30818): New flag to flutter drive to skip installing fresh app on device * [flutter#30867](https://github.com/flutter/flutter/pull/30867): Add toggle for debugProfileWidgetBuilds * [flutter#27034](https://github.com/flutter/flutter/pull/27034): Updated package template .gitignore file * [flutter#30115](https://github.com/flutter/flutter/pull/30115): Forward missing pub commands * [flutter#30254](https://github.com/flutter/flutter/pull/30254): Reland: Ensure that flutter run/drive/test/update_packages only downloads required artifacts * [flutter#30153](https://github.com/flutter/flutter/pull/30153): Allow disabling experimental commands, devices on stable branch * [flutter#30428](https://github.com/flutter/flutter/pull/30428): Update repair command for Arch Linux Further, the IDE plugins for Flutter have had a number of updates since the last stable release of Flutter. * Visual Studio Code: [February 21, 2019 (2.23.1)](https://dartcode.org/releases/v2-23/) * Visual Studio Code: [February 27, 2019 (2.24.0)](https://dartcode.org/releases/v2-24/) * IntelliJ/Android Studio: [March 29, 2019 (M34)](https://groups.google.com/forum/#!msg/flutter-dev/-g7MlcL7u9s/VwZtnh-XAgAJ) * Visual Studio Code: [April 17, 2019 (2.25.1)](https://dartcode.org/releases/v2-25/) * IntelliJ/Android Studio: [April 26, 2019 (M35)](https://groups.google.com/forum/#!topic/flutter-dev/qZNjCI_2BLE) * Visual Studio Code: [May 1, 2019 (2.26.1)](https://dartcode.org/releases/v2-26/ ) ## Dynamic Update (aka Code Push) As a final note, we're nearly at the midpoint of the year, when it's time to reassess the areas where we can have the most important, we've decided to drop plans for dynamic updates (aka code push) from our 2019 roadmap. If you're interested in the reasons why, you can read [the detailed explanation](https://github.com/flutter/flutter/issues/14330#issuecomment-485565194). Dropping this work allows us to increase our focus on quality as well as our experiments in Flutter for web and Flutter for desktop. ## Full Issue List You can see [the full list of PRs committed in this release](/release/release-notes/changelogs/changelog-1.5.4).
website/src/release/release-notes/release-notes-1.5.4.md/0
{ "file_path": "website/src/release/release-notes/release-notes-1.5.4.md", "repo_id": "website", "token_count": 7920 }
1,320
--- title: Upgrading Flutter short-title: Upgrading description: How to upgrade Flutter. --- No matter which one of the Flutter release channels you follow, you can use the `flutter` command to upgrade your Flutter SDK or the packages that your app depends on. ## Upgrading the Flutter SDK To update the Flutter SDK use the `flutter upgrade` command: ```terminal $ flutter upgrade ``` This command gets the most recent version of the Flutter SDK that's available on your current Flutter channel. If you are using the **stable** channel and want an even more recent version of the Flutter SDK, switch to the **beta** channel using `flutter channel beta`, and then run `flutter upgrade`. ### Keeping informed We publish [migration guides][] for known breaking changes. We send announcements regarding these changes to the [Flutter announcements mailing list][flutter-announce]. To avoid being broken by future versions of Flutter, consider submitting your tests to our [test registry][]. ## Switching Flutter channels Flutter has two release channels: **stable** and **beta**. ### The **stable** channel We recommend the **stable** channel for new users and for production app releases. The team updates this channel about every three months. The channel might receive occasional hot fixes for high-severity or high-impact issues. The continuous integration for the Flutter team's plugins and packages includes testing against the latest **stable** release. The latest documentation for the **stable** branch is at: <https://api.flutter.dev> ### The **beta** channel The **beta** channel has the latest stable release. This is the most recent version of Flutter that we have heavily tested. This channel has passed all our public testing, has been verified against test suites for Google products that use Flutter, and has been vetted against [contributed private test suites][test registry]. The **beta** channel receives regular hot fixes to address newly discovered important issues. The **beta** channel is essentially the same as the **stable** channel but updated monthly instead of quarterly. Indeed, when the **stable** channel is updated, it is updated to the latest **beta** release. ### Other channels We currently have one other channel, **master**. People who [contribute to Flutter][] use this channel. This channel is not as thoroughly tested as the **beta** and **stable** channels. We do not recommend using this channel as it is more likely to contain serious regressions. The latest documentation for the **master** branch is at: <https://main-api.flutter.dev> ### Changing channels To view your current channel, use the following command: ```terminal $ flutter channel ``` To change to another channel, use `flutter channel <channel-name>`. Once you've changed your channel, use `flutter upgrade` to download the latest Flutter SDK and dependent packages for that channel. For example: ```terminal $ flutter channel beta $ flutter upgrade ``` {{site.alert.note}} If you need a specific version of the Flutter SDK, you can download it from the [Flutter SDK archive][]. {{site.alert.end}} ## Upgrading packages If you've modified your `pubspec.yaml` file, or you want to update only the packages that your app depends upon (instead of both the packages and Flutter itself), then use one of the `flutter pub` commands. To update to the _latest compatible versions_ of all the dependencies listed in the `pubspec.yaml` file, use the `upgrade` command: ```terminal $ flutter pub upgrade ``` To update to the _latest possible version_ of all the dependencies listed in the `pubspec.yaml` file, use the `upgrade --major-versions` command: ```terminal $ flutter pub upgrade --major-versions ``` This also automatically update the constraints in the `pubspec.yaml` file. To identify out-of-date package dependencies and get advice on how to update them, use the `outdated` command. For details, see the Dart [`pub outdated` documentation]({{site.dart-site}}/tools/pub/cmd/pub-outdated). ```terminal $ flutter pub outdated ``` [Flutter SDK archive]: /release/archive [flutter-announce]: {{site.groups}}/forum/#!forum/flutter-announce [pubspec.yaml]: {{site.dart-site}}/tools/pub/pubspec [test registry]: {{site.repo.organization}}/tests [contribute to Flutter]: {{site.repo.flutter}}/blob/main/CONTRIBUTING.md [migration guides]: /release/breaking-changes
website/src/release/upgrade.md/0
{ "file_path": "website/src/release/upgrade.md", "repo_id": "website", "token_count": 1171 }
1,321
--- title: Search flutter.dev short-title: Search description: The search page for flutter.dev. toc: false --- Want results from additional Flutter-related sites, like api.flutter.dev and dart.dev? <a href="/search-all">Search more sites.</a> <div class="d-flex searchbar"> <script async src="https://cse.google.com/cse.js?cx=d67ad728b5ad14785"></script> <div class="gcse-search"></div> </div>
website/src/search.html/0
{ "file_path": "website/src/search.html", "repo_id": "website", "token_count": 138 }
1,322
```nocode flutter: RenderView#02c80 flutter: │ debug mode enabled - macos flutter: │ view size: Size(800.0, 600.0) (in physical pixels) flutter: │ device pixel ratio: 1.0 (physical pixels per logical pixel) flutter: │ configuration: Size(800.0, 600.0) at 1.0x (in logical pixels) flutter: │ flutter: └─child: RenderSemanticsAnnotations#fe6b5 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← flutter: │ HeroControllerScope ← ScrollConfiguration ← MaterialApp ← flutter: │ MediaQuery ← _MediaQueryFromView ← _ViewScope ← flutter: │ View-[GlobalObjectKey FlutterView#6cffa] ← [root] flutter: │ parentData: <none> flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#6edef flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ _SharedAppModel ← SharedAppData ← UnmanagedRestorationScope ← flutter: │ RestorationScope ← UnmanagedRestorationScope ← flutter: │ RootRestorationScope ← WidgetsApp-[GlobalObjectKey flutter: │ _MaterialAppState#5c303] ← Semantics ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#e8ce8 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ DefaultTextEditingShortcuts ← Semantics ← _FocusInheritedScope flutter: │ ← Focus ← Shortcuts ← _SharedAppModel ← SharedAppData ← flutter: │ UnmanagedRestorationScope ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#fc545 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ DefaultTextEditingShortcuts ← Semantics ← _FocusInheritedScope flutter: │ ← Focus ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderTapRegionSurface#ff857 flutter: │ needs compositing flutter: │ creator: TapRegionSurface ← _FocusInheritedScope ← Focus ← flutter: │ FocusTraversalGroup ← _ActionsScope ← Actions ← Semantics ← flutter: │ _FocusInheritedScope ← Focus ← Shortcuts ← Semantics ← flutter: │ _FocusInheritedScope ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ behavior: deferToChild flutter: │ flutter: └─child: RenderSemanticsAnnotations#fe316 flutter: │ needs compositing flutter: │ creator: Semantics ← _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ _ShortcutRegistrarScope ← ShortcutRegistrar ← TapRegionSurface flutter: │ ← _FocusInheritedScope ← Focus ← FocusTraversalGroup ← flutter: │ _ActionsScope ← Actions ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderSemanticsAnnotations#fa55c flutter: │ needs compositing flutter: │ creator: Semantics ← Localizations ← Semantics ← flutter: │ _FocusInheritedScope ← Focus ← Shortcuts ← flutter: │ _ShortcutRegistrarScope ← ShortcutRegistrar ← TapRegionSurface flutter: │ ← _FocusInheritedScope ← Focus ← FocusTraversalGroup ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderCustomPaint#4b256 flutter: │ needs compositing flutter: │ creator: CustomPaint ← Banner ← CheckedModeBanner ← Title ← flutter: │ Directionality ← _LocalizationsScope-[GlobalKey#4a3aa] ← flutter: │ Semantics ← Localizations ← Semantics ← _FocusInheritedScope ← flutter: │ Focus ← Shortcuts ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ painter: null flutter: │ foregroundPainter: BannerPainter#1bfd7(Instance of flutter: │ '_SystemFontsNotifier') flutter: │ flutter: └─child: RenderSemanticsAnnotations#f470f flutter: │ needs compositing flutter: │ creator: Semantics ← FocusScope ← DefaultSelectionStyle ← flutter: │ IconTheme ← IconTheme ← _InheritedCupertinoTheme ← flutter: │ CupertinoTheme ← _InheritedTheme ← Theme ← AnimatedTheme ← flutter: │ DefaultSelectionStyle ← _ScaffoldMessengerScope ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ flutter: └─child: RenderPointerListener#f59c8 flutter: │ needs compositing flutter: │ creator: Listener ← HeroControllerScope ← flutter: │ Navigator-[GlobalObjectKey<NavigatorState> flutter: │ _WidgetsAppState#0d73a] ← _FocusInheritedScope ← Semantics ← flutter: │ FocusScope ← DefaultSelectionStyle ← IconTheme ← IconTheme ← flutter: │ _InheritedCupertinoTheme ← CupertinoTheme ← _InheritedTheme ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ behavior: deferToChild flutter: │ listeners: down, up, cancel flutter: │ flutter: └─child: RenderAbsorbPointer#c91bd flutter: │ needs compositing flutter: │ creator: AbsorbPointer ← Listener ← HeroControllerScope ← flutter: │ Navigator-[GlobalObjectKey<NavigatorState> flutter: │ _WidgetsAppState#0d73a] ← _FocusInheritedScope ← Semantics ← flutter: │ FocusScope ← DefaultSelectionStyle ← IconTheme ← IconTheme ← flutter: │ _InheritedCupertinoTheme ← CupertinoTheme ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ absorbing: false flutter: │ ignoringSemantics: null flutter: │ flutter: └─child: _RenderTheater#07897 flutter: │ needs compositing flutter: │ creator: _Theater ← flutter: │ Overlay-[LabeledGlobalKey<OverlayState>#49a93] ← flutter: │ UnmanagedRestorationScope ← _FocusInheritedScope ← Focus ← flutter: │ _FocusInheritedScope ← Focus ← FocusTraversalGroup ← flutter: │ AbsorbPointer ← Listener ← HeroControllerScope ← flutter: │ Navigator-[GlobalObjectKey<NavigatorState> flutter: │ _WidgetsAppState#0d73a] ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ skipCount: 0 flutter: │ textDirection: ltr flutter: │ flutter: ├─onstage 1: RenderIgnorePointer#3b659 flutter: │ │ creator: IgnorePointer ← _RenderTheaterMarker ← flutter: │ │ _EffectiveTickerMode ← TickerMode ← flutter: │ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#a47f4] flutter: │ │ ← _Theater ← Overlay-[LabeledGlobalKey<OverlayState>#49a93] ← flutter: │ │ UnmanagedRestorationScope ← _FocusInheritedScope ← Focus ← flutter: │ │ _FocusInheritedScope ← Focus ← ⋯ flutter: │ │ parentData: not positioned; offset=Offset(0.0, 0.0) (can use flutter: │ │ size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ ignoring: false flutter: │ │ ignoringSemantics: null flutter: │ │ flutter: │ └─child: RenderBlockSemantics#7586c flutter: │ │ creator: BlockSemantics ← ModalBarrier ← IgnorePointer ← flutter: │ │ _RenderTheaterMarker ← _EffectiveTickerMode ← TickerMode ← flutter: │ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#a47f4] flutter: │ │ ← _Theater ← Overlay-[LabeledGlobalKey<OverlayState>#49a93] ← flutter: │ │ UnmanagedRestorationScope ← _FocusInheritedScope ← Focus ← ⋯ flutter: │ │ parentData: <none> (can use size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ blocks semantics of earlier render objects below the common flutter: │ │ boundary flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ blocking: true flutter: │ │ flutter: │ └─child: RenderExcludeSemantics#c1d3f flutter: │ │ creator: ExcludeSemantics ← BlockSemantics ← ModalBarrier ← flutter: │ │ IgnorePointer ← _RenderTheaterMarker ← _EffectiveTickerMode ← flutter: │ │ TickerMode ← flutter: │ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#a47f4] flutter: │ │ ← _Theater ← Overlay-[LabeledGlobalKey<OverlayState>#49a93] ← flutter: │ │ UnmanagedRestorationScope ← _FocusInheritedScope ← ⋯ flutter: │ │ parentData: <none> (can use size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ excluding: true flutter: │ │ flutter: │ └─child: RenderSemanticsGestureHandler#70b16 flutter: │ │ creator: _GestureSemantics ← RawGestureDetector ← flutter: │ │ _ModalBarrierGestureDetector ← ExcludeSemantics ← flutter: │ │ BlockSemantics ← ModalBarrier ← IgnorePointer ← flutter: │ │ _RenderTheaterMarker ← _EffectiveTickerMode ← TickerMode ← flutter: │ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#a47f4] flutter: │ │ ← _Theater ← ⋯ flutter: │ │ parentData: <none> (can use size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ behavior: opaque flutter: │ │ gestures: <none> flutter: │ │ flutter: │ └─child: RenderPointerListener#1f34a flutter: │ │ creator: Listener ← _GestureSemantics ← RawGestureDetector ← flutter: │ │ _ModalBarrierGestureDetector ← ExcludeSemantics ← flutter: │ │ BlockSemantics ← ModalBarrier ← IgnorePointer ← flutter: │ │ _RenderTheaterMarker ← _EffectiveTickerMode ← TickerMode ← flutter: │ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#a47f4] flutter: │ │ ← ⋯ flutter: │ │ parentData: <none> (can use size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ behavior: opaque flutter: │ │ listeners: down, panZoomStart flutter: │ │ flutter: │ └─child: RenderSemanticsAnnotations#73467 flutter: │ │ creator: Semantics ← Listener ← _GestureSemantics ← flutter: │ │ RawGestureDetector ← _ModalBarrierGestureDetector ← flutter: │ │ ExcludeSemantics ← BlockSemantics ← ModalBarrier ← flutter: │ │ IgnorePointer ← _RenderTheaterMarker ← _EffectiveTickerMode ← flutter: │ │ TickerMode ← ⋯ flutter: │ │ parentData: <none> (can use size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ flutter: │ └─child: RenderMouseRegion#560dc flutter: │ │ creator: MouseRegion ← Semantics ← Listener ← _GestureSemantics ← flutter: │ │ RawGestureDetector ← _ModalBarrierGestureDetector ← flutter: │ │ ExcludeSemantics ← BlockSemantics ← ModalBarrier ← flutter: │ │ IgnorePointer ← _RenderTheaterMarker ← _EffectiveTickerMode ← ⋯ flutter: │ │ parentData: <none> (can use size) flutter: │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ │ size: Size(800.0, 600.0) flutter: │ │ behavior: opaque flutter: │ │ listeners: <none> flutter: │ │ cursor: SystemMouseCursor(basic) flutter: │ │ flutter: │ └─child: RenderConstrainedBox#01e8c flutter: │ creator: ConstrainedBox ← MouseRegion ← Semantics ← Listener ← flutter: │ _GestureSemantics ← RawGestureDetector ← flutter: │ _ModalBarrierGestureDetector ← ExcludeSemantics ← flutter: │ BlockSemantics ← ModalBarrier ← IgnorePointer ← flutter: │ _RenderTheaterMarker ← ⋯ flutter: │ parentData: <none> (can use size) flutter: │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: │ size: Size(800.0, 600.0) flutter: │ additionalConstraints: BoxConstraints(biggest) flutter: │ flutter: ├─onstage 2: RenderSemanticsAnnotations#8187b flutter: ╎ │ needs compositing flutter: ╎ │ creator: Semantics ← _RenderTheaterMarker ← _EffectiveTickerMode flutter: ╎ │ ← TickerMode ← flutter: ╎ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#8cd54] flutter: ╎ │ ← _Theater ← Overlay-[LabeledGlobalKey<OverlayState>#49a93] ← flutter: ╎ │ UnmanagedRestorationScope ← _FocusInheritedScope ← Focus ← flutter: ╎ │ _FocusInheritedScope ← Focus ← ⋯ flutter: ╎ │ parentData: not positioned; offset=Offset(0.0, 0.0) (can use flutter: ╎ │ size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ flutter: ╎ └─child: RenderOffstage#f211d flutter: ╎ │ needs compositing flutter: ╎ │ creator: Offstage ← _ModalScopeStatus ← UnmanagedRestorationScope flutter: ╎ │ ← RestorationScope ← AnimatedBuilder ← flutter: ╎ │ _ModalScope<dynamic>-[LabeledGlobalKey<_ModalScopeState<dynamic>>#db401] flutter: ╎ │ ← Semantics ← _RenderTheaterMarker ← _EffectiveTickerMode ← flutter: ╎ │ TickerMode ← flutter: ╎ │ _OverlayEntryWidget-[LabeledGlobalKey<_OverlayEntryWidgetState>#8cd54] flutter: ╎ │ ← _Theater ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ offstage: false flutter: ╎ │ flutter: ╎ └─child: RenderSemanticsAnnotations#9436c flutter: ╎ │ needs compositing flutter: ╎ │ creator: Semantics ← FocusScope ← PrimaryScrollController ← flutter: ╎ │ _ActionsScope ← Actions ← Builder ← PageStorage ← Offstage ← flutter: ╎ │ _ModalScopeStatus ← UnmanagedRestorationScope ← flutter: ╎ │ RestorationScope ← AnimatedBuilder ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ flutter: ╎ └─child: RenderRepaintBoundary#f8f28 flutter: ╎ │ needs compositing flutter: ╎ │ creator: RepaintBoundary ← _FocusInheritedScope ← Semantics ← flutter: ╎ │ FocusScope ← PrimaryScrollController ← _ActionsScope ← Actions flutter: ╎ │ ← Builder ← PageStorage ← Offstage ← _ModalScopeStatus ← flutter: ╎ │ UnmanagedRestorationScope ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ layer: OffsetLayer#e73b7 flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ metrics: 66.7% useful (1 bad vs 2 good) flutter: ╎ │ diagnosis: insufficient data to draw conclusion (less than five flutter: ╎ │ repaints) flutter: ╎ │ flutter: ╎ └─child: RenderFractionalTranslation#c3a54 flutter: ╎ │ needs compositing flutter: ╎ │ creator: FractionalTranslation ← SlideTransition ← flutter: ╎ │ CupertinoPageTransition ← AnimatedBuilder ← RepaintBoundary ← flutter: ╎ │ _FocusInheritedScope ← Semantics ← FocusScope ← flutter: ╎ │ PrimaryScrollController ← _ActionsScope ← Actions ← Builder ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ translation: Offset(0.0, 0.0) flutter: ╎ │ transformHitTests: false flutter: ╎ │ flutter: ╎ └─child: RenderFractionalTranslation#7fcf2 flutter: ╎ │ needs compositing flutter: ╎ │ creator: FractionalTranslation ← SlideTransition ← flutter: ╎ │ FractionalTranslation ← SlideTransition ← flutter: ╎ │ CupertinoPageTransition ← AnimatedBuilder ← RepaintBoundary ← flutter: ╎ │ _FocusInheritedScope ← Semantics ← FocusScope ← flutter: ╎ │ PrimaryScrollController ← _ActionsScope ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ translation: Offset(0.0, 0.0) flutter: ╎ │ transformHitTests: true flutter: ╎ │ flutter: ╎ └─child: RenderDecoratedBox#713ec flutter: ╎ │ needs compositing flutter: ╎ │ creator: DecoratedBox ← DecoratedBoxTransition ← flutter: ╎ │ FractionalTranslation ← SlideTransition ← FractionalTranslation flutter: ╎ │ ← SlideTransition ← CupertinoPageTransition ← AnimatedBuilder ← flutter: ╎ │ RepaintBoundary ← _FocusInheritedScope ← Semantics ← FocusScope flutter: ╎ │ ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ ├─decoration: _CupertinoEdgeShadowDecoration flutter: ╎ │ colors: Color(0x04000000), Color(0x00000000) flutter: ╎ │ flutter: ╎ │ configuration: ImageConfiguration(bundle: flutter: ╎ │ PlatformAssetBundle#164ca(), devicePixelRatio: 1.0, locale: flutter: ╎ │ en_US, textDirection: TextDirection.ltr, platform: macOS) flutter: ╎ │ flutter: ╎ └─child: RenderStack#83b13 flutter: ╎ │ needs compositing flutter: ╎ │ creator: Stack ← _CupertinoBackGestureDetector<dynamic> ← flutter: ╎ │ DecoratedBox ← DecoratedBoxTransition ← FractionalTranslation ← flutter: ╎ │ SlideTransition ← FractionalTranslation ← SlideTransition ← flutter: ╎ │ CupertinoPageTransition ← AnimatedBuilder ← RepaintBoundary ← flutter: ╎ │ _FocusInheritedScope ← ⋯ flutter: ╎ │ parentData: <none> (can use size) flutter: ╎ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ size: Size(800.0, 600.0) flutter: ╎ │ alignment: AlignmentDirectional.topStart flutter: ╎ │ textDirection: ltr flutter: ╎ │ fit: passthrough flutter: ╎ │ flutter: ╎ ├─child 1: RenderIgnorePointer#ad50f flutter: ╎ │ │ needs compositing flutter: ╎ │ │ creator: IgnorePointer ← AnimatedBuilder ← Stack ← flutter: ╎ │ │ _CupertinoBackGestureDetector<dynamic> ← DecoratedBox ← flutter: ╎ │ │ DecoratedBoxTransition ← FractionalTranslation ← flutter: ╎ │ │ SlideTransition ← FractionalTranslation ← SlideTransition ← flutter: ╎ │ │ CupertinoPageTransition ← AnimatedBuilder ← ⋯ flutter: ╎ │ │ parentData: not positioned; offset=Offset(0.0, 0.0) (can use flutter: ╎ │ │ size) flutter: ╎ │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ │ size: Size(800.0, 600.0) flutter: ╎ │ │ ignoring: false flutter: ╎ │ │ ignoringSemantics: null flutter: ╎ │ │ flutter: ╎ │ └─child: RenderRepaintBoundary#29754 flutter: ╎ │ │ needs compositing flutter: ╎ │ │ creator: RepaintBoundary-[GlobalKey#75409] ← IgnorePointer ← flutter: ╎ │ │ AnimatedBuilder ← Stack ← flutter: ╎ │ │ _CupertinoBackGestureDetector<dynamic> ← DecoratedBox ← flutter: ╎ │ │ DecoratedBoxTransition ← FractionalTranslation ← flutter: ╎ │ │ SlideTransition ← FractionalTranslation ← SlideTransition ← flutter: ╎ │ │ CupertinoPageTransition ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ │ layer: OffsetLayer#fa835 flutter: ╎ │ │ size: Size(800.0, 600.0) flutter: ╎ │ │ metrics: 90.9% useful (1 bad vs 10 good) flutter: ╎ │ │ diagnosis: this is an outstandingly useful repaint boundary and flutter: ╎ │ │ should definitely be kept flutter: ╎ │ │ flutter: ╎ │ └─child: RenderSemanticsAnnotations#95566 flutter: ╎ │ │ creator: Semantics ← Builder ← RepaintBoundary-[GlobalKey#75409] flutter: ╎ │ │ ← IgnorePointer ← AnimatedBuilder ← Stack ← flutter: ╎ │ │ _CupertinoBackGestureDetector<dynamic> ← DecoratedBox ← flutter: ╎ │ │ DecoratedBoxTransition ← FractionalTranslation ← flutter: ╎ │ │ SlideTransition ← FractionalTranslation ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ │ size: Size(800.0, 600.0) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderPhysicalModel#bc9d7 flutter: ╎ │ │ creator: PhysicalModel ← AnimatedPhysicalModel ← Material ← flutter: ╎ │ │ AppHome ← Semantics ← Builder ← flutter: ╎ │ │ RepaintBoundary-[GlobalKey#75409] ← IgnorePointer ← flutter: ╎ │ │ AnimatedBuilder ← Stack ← flutter: ╎ │ │ _CupertinoBackGestureDetector<dynamic> ← DecoratedBox ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ │ size: Size(800.0, 600.0) flutter: ╎ │ │ elevation: 0.0 flutter: ╎ │ │ color: Color(0xfffafafa) flutter: ╎ │ │ shadowColor: Color(0xfffafafa) flutter: ╎ │ │ shape: BoxShape.rectangle flutter: ╎ │ │ borderRadius: BorderRadius.zero flutter: ╎ │ │ flutter: ╎ │ └─child: _RenderInkFeatures#ac819 flutter: ╎ │ │ creator: _InkFeatures-[GlobalKey#d721e ink renderer] ← flutter: ╎ │ │ NotificationListener<LayoutChangedNotification> ← PhysicalModel flutter: ╎ │ │ ← AnimatedPhysicalModel ← Material ← AppHome ← Semantics ← flutter: ╎ │ │ Builder ← RepaintBoundary-[GlobalKey#75409] ← IgnorePointer ← flutter: ╎ │ │ AnimatedBuilder ← Stack ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ │ size: Size(800.0, 600.0) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderPositionedBox#dc1df flutter: ╎ │ │ creator: Center ← DefaultTextStyle ← AnimatedDefaultTextStyle ← flutter: ╎ │ │ _InkFeatures-[GlobalKey#d721e ink renderer] ← flutter: ╎ │ │ NotificationListener<LayoutChangedNotification> ← PhysicalModel flutter: ╎ │ │ ← AnimatedPhysicalModel ← Material ← AppHome ← Semantics ← flutter: ╎ │ │ Builder ← RepaintBoundary-[GlobalKey#75409] ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(w=800.0, h=600.0) flutter: ╎ │ │ size: Size(800.0, 600.0) flutter: ╎ │ │ alignment: Alignment.center flutter: ╎ │ │ textDirection: ltr flutter: ╎ │ │ widthFactor: expand flutter: ╎ │ │ heightFactor: expand flutter: ╎ │ │ flutter: ╎ │ └─child: RenderSemanticsAnnotations#a0a4b relayoutBoundary=up1 flutter: ╎ │ │ creator: Semantics ← TextButton ← Center ← DefaultTextStyle ← flutter: ╎ │ │ AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#d721e ink flutter: ╎ │ │ renderer] ← NotificationListener<LayoutChangedNotification> ← flutter: ╎ │ │ PhysicalModel ← AnimatedPhysicalModel ← Material ← AppHome ← flutter: ╎ │ │ Semantics ← ⋯ flutter: ╎ │ │ parentData: offset=Offset(329.0, 286.0) (can use size) flutter: ╎ │ │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0) flutter: ╎ │ │ semantic boundary flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ flutter: ╎ │ └─child: _RenderInputPadding#4672f relayoutBoundary=up2 flutter: ╎ │ │ creator: _InputPadding ← Semantics ← TextButton ← Center ← flutter: ╎ │ │ DefaultTextStyle ← AnimatedDefaultTextStyle ← flutter: ╎ │ │ _InkFeatures-[GlobalKey#d721e ink renderer] ← flutter: ╎ │ │ NotificationListener<LayoutChangedNotification> ← PhysicalModel flutter: ╎ │ │ ← AnimatedPhysicalModel ← Material ← AppHome ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderConstrainedBox#425d6 relayoutBoundary=up3 flutter: ╎ │ │ creator: ConstrainedBox ← _InputPadding ← Semantics ← TextButton flutter: ╎ │ │ ← Center ← DefaultTextStyle ← AnimatedDefaultTextStyle ← flutter: ╎ │ │ _InkFeatures-[GlobalKey#d721e ink renderer] ← flutter: ╎ │ │ NotificationListener<LayoutChangedNotification> ← PhysicalModel flutter: ╎ │ │ ← AnimatedPhysicalModel ← Material ← ⋯ flutter: ╎ │ │ parentData: offset=Offset(0.0, 0.0) (can use size) flutter: ╎ │ │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ additionalConstraints: BoxConstraints(56.0<=w<=Infinity, flutter: ╎ │ │ 28.0<=h<=Infinity) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderPhysicalShape#8e171 relayoutBoundary=up4 flutter: ╎ │ │ creator: PhysicalShape ← _MaterialInterior ← Material ← flutter: ╎ │ │ ConstrainedBox ← _InputPadding ← Semantics ← TextButton ← flutter: ╎ │ │ Center ← DefaultTextStyle ← AnimatedDefaultTextStyle ← flutter: ╎ │ │ _InkFeatures-[GlobalKey#d721e ink renderer] ← flutter: ╎ │ │ NotificationListener<LayoutChangedNotification> ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ elevation: 0.0 flutter: ╎ │ │ color: Color(0x00000000) flutter: ╎ │ │ shadowColor: Color(0x00000000) flutter: ╎ │ │ clipper: ShapeBorderClipper flutter: ╎ │ │ flutter: ╎ │ └─child: RenderCustomPaint#eea46 relayoutBoundary=up5 flutter: ╎ │ │ creator: CustomPaint ← _ShapeBorderPaint ← PhysicalShape ← flutter: ╎ │ │ _MaterialInterior ← Material ← ConstrainedBox ← _InputPadding ← flutter: ╎ │ │ Semantics ← TextButton ← Center ← DefaultTextStyle ← flutter: ╎ │ │ AnimatedDefaultTextStyle ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ painter: null flutter: ╎ │ │ foregroundPainter: _ShapeBorderPainter#ac724() flutter: ╎ │ │ flutter: ╎ │ └─child: _RenderInkFeatures#b19a7 relayoutBoundary=up6 flutter: ╎ │ │ creator: _InkFeatures-[GlobalKey#87971 ink renderer] ← flutter: ╎ │ │ NotificationListener<LayoutChangedNotification> ← CustomPaint ← flutter: ╎ │ │ _ShapeBorderPaint ← PhysicalShape ← _MaterialInterior ← flutter: ╎ │ │ Material ← ConstrainedBox ← _InputPadding ← Semantics ← flutter: ╎ │ │ TextButton ← Center ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderSemanticsAnnotations#4d1b3 relayoutBoundary=up7 flutter: ╎ │ │ creator: Semantics ← _FocusInheritedScope ← Focus ← _ActionsScope flutter: ╎ │ │ ← Actions ← _ParentInkResponseProvider ← flutter: ╎ │ │ _InkResponseStateWidget ← InkWell ← DefaultTextStyle ← flutter: ╎ │ │ AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#87971 ink flutter: ╎ │ │ renderer] ← NotificationListener<LayoutChangedNotification> ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderMouseRegion#e5b3f relayoutBoundary=up8 flutter: ╎ │ │ creator: MouseRegion ← Semantics ← _FocusInheritedScope ← Focus ← flutter: ╎ │ │ _ActionsScope ← Actions ← _ParentInkResponseProvider ← flutter: ╎ │ │ _InkResponseStateWidget ← InkWell ← DefaultTextStyle ← flutter: ╎ │ │ AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#87971 ink flutter: ╎ │ │ renderer] ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ behavior: opaque flutter: ╎ │ │ listeners: enter, exit flutter: ╎ │ │ cursor: SystemMouseCursor(click) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderSemanticsAnnotations#deb9b relayoutBoundary=up9 flutter: ╎ │ │ creator: Semantics ← DefaultSelectionStyle ← Builder ← flutter: ╎ │ │ MouseRegion ← Semantics ← _FocusInheritedScope ← Focus ← flutter: ╎ │ │ _ActionsScope ← Actions ← _ParentInkResponseProvider ← flutter: ╎ │ │ _InkResponseStateWidget ← InkWell ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ flutter: ╎ │ └─child: RenderPointerListener#2017a relayoutBoundary=up10 flutter: ╎ │ │ creator: Listener ← RawGestureDetector ← GestureDetector ← flutter: ╎ │ │ Semantics ← DefaultSelectionStyle ← Builder ← MouseRegion ← flutter: ╎ │ │ Semantics ← _FocusInheritedScope ← Focus ← _ActionsScope ← flutter: ╎ │ │ Actions ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ behavior: opaque flutter: ╎ │ │ listeners: down, panZoomStart flutter: ╎ │ │ flutter: ╎ │ └─child: RenderPadding#8455f relayoutBoundary=up11 flutter: ╎ │ │ creator: Padding ← IconTheme ← Builder ← Listener ← flutter: ╎ │ │ RawGestureDetector ← GestureDetector ← Semantics ← flutter: ╎ │ │ DefaultSelectionStyle ← Builder ← MouseRegion ← Semantics ← flutter: ╎ │ │ _FocusInheritedScope ← ⋯ flutter: ╎ │ │ parentData: <none> (can use size) flutter: ╎ │ │ constraints: BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(142.0, 28.0) flutter: ╎ │ │ padding: EdgeInsets(8.0, 0.0, 8.0, 0.0) flutter: ╎ │ │ textDirection: ltr flutter: ╎ │ │ flutter: ╎ │ └─child: RenderPositionedBox#80b8d relayoutBoundary=up12 flutter: ╎ │ │ creator: Align ← Padding ← IconTheme ← Builder ← Listener ← flutter: ╎ │ │ RawGestureDetector ← GestureDetector ← Semantics ← flutter: ╎ │ │ DefaultSelectionStyle ← Builder ← MouseRegion ← Semantics ← ⋯ flutter: ╎ │ │ parentData: offset=Offset(8.0, 0.0) (can use size) flutter: ╎ │ │ constraints: BoxConstraints(40.0<=w<=784.0, 28.0<=h<=600.0) flutter: ╎ │ │ size: Size(126.0, 28.0) flutter: ╎ │ │ alignment: Alignment.center flutter: ╎ │ │ textDirection: ltr flutter: ╎ │ │ widthFactor: 1.0 flutter: ╎ │ │ heightFactor: 1.0 flutter: ╎ │ │ flutter: ╎ │ └─child: RenderParagraph#59bc2 relayoutBoundary=up13 flutter: ╎ │ │ creator: RichText ← Text ← Align ← Padding ← IconTheme ← Builder flutter: ╎ │ │ ← Listener ← RawGestureDetector ← GestureDetector ← Semantics ← flutter: ╎ │ │ DefaultSelectionStyle ← Builder ← ⋯ flutter: ╎ │ │ parentData: offset=Offset(0.0, 6.0) (can use size) flutter: ╎ │ │ constraints: BoxConstraints(0.0<=w<=784.0, 0.0<=h<=600.0) flutter: ╎ │ │ size: Size(126.0, 16.0) flutter: ╎ │ │ textAlign: start flutter: ╎ │ │ textDirection: ltr flutter: ╎ │ │ softWrap: wrapping at box width flutter: ╎ │ │ overflow: clip flutter: ╎ │ │ locale: en_US flutter: ╎ │ │ maxLines: unlimited flutter: ╎ │ ╘═╦══ text ═══ flutter: ╎ │ ║ TextSpan: flutter: ╎ │ ║ debugLabel: ((englishLike labelLarge 2014).merge(blackRedwoodCity flutter: ╎ │ ║ labelLarge)).copyWith flutter: ╎ │ ║ inherit: false flutter: ╎ │ ║ color: MaterialColor(primary value: Color(0xff2196f3)) flutter: ╎ │ ║ family: .AppleSystemUIFont flutter: ╎ │ ║ size: 14.0 flutter: ╎ │ ║ weight: 500 flutter: ╎ │ ║ baseline: alphabetic flutter: ╎ │ ║ decoration: TextDecoration.none flutter: ╎ │ ║ "Dump Render Tree" flutter: ╎ │ ╚═══════════ flutter: ╎ └─child 2: RenderPointerListener#db4b5 flutter: ╎ creator: Listener ← Positioned ← PositionedDirectional ← Stack ← flutter: ╎ _CupertinoBackGestureDetector<dynamic> ← DecoratedBox ← flutter: ╎ DecoratedBoxTransition ← FractionalTranslation ← flutter: ╎ SlideTransition ← FractionalTranslation ← SlideTransition ← flutter: ╎ CupertinoPageTransition ← ⋯ flutter: ╎ parentData: top=0.0; bottom=0.0; left=0.0; width=20.0; flutter: ╎ offset=Offset(0.0, 0.0) (can use size) flutter: ╎ constraints: BoxConstraints(w=20.0, h=600.0) flutter: ╎ size: Size(20.0, 600.0) flutter: ╎ behavior: translucent flutter: ╎ listeners: down flutter: ╎ flutter: └╌no offstage children flutter: ```
website/src/testing/trees/render-tree.md/0
{ "file_path": "website/src/testing/trees/render-tree.md", "repo_id": "website", "token_count": 35317 }
1,323
--- title: Install and run DevTools from the command line description: Learn how to install and use DevTools from the command line. --- To run Dart DevTools from the CLI, you must have `dart` on your path. Then you can run the following command to launch DevTools: ``` dart devtools ``` To upgrade DevTools, upgrade your Dart SDK. If a newer Dart SDK includes a newer version of DevTools, `dart devtools` will automatically launch this version. If `which dart` points to the Dart SDK included in your Flutter SDK, then DevTools will be upgraded when you upgrade your Flutter SDK to a newer version. When you run DevTools from the command line, you should see output that looks something like: ``` Serving DevTools at http://127.0.0.1:9100 ``` ## Start an application to debug Next, start an app to connect to. This can be either a Flutter application or a Dart command-line application. The command below specifies a Flutter app: ``` cd path/to/flutter/app flutter run ``` You need to have a device connected, or a simulator open, for `flutter run` to work. Once the app starts, you'll see a message in your terminal that looks like the following: ``` An Observatory debugger and profiler on macOS is available at: http://127.0.0.1:52129/QjqebSY4lQ8=/ The Flutter DevTools debugger and profiler on macOS is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:52129/QjqebSY4lQ8=/ ``` Open the DevTools instance connected to your app by opening the second link in Chrome. This URL contains a security token, so it's different for each run of your app. This means that if you stop your application and re-run it, you need to connect to DevTools again with the new URL. ## Connect to a new app instance If your app stops running or you opened DevTools manually, you should see a **Connect** dialog: ![Screenshot of the DevTools connect dialog](/assets/images/docs/tools/devtools/connect_dialog.png){:width="100%"} You can manually connect DevTools to a new app instance by copying the Observatory link you got from running your app, such as `http://127.0.0.1:52129/QjqebSY4lQ8=/` and pasting it into the connect dialog:
website/src/tools/devtools/cli.md/0
{ "file_path": "website/src/tools/devtools/cli.md", "repo_id": "website", "token_count": 623 }
1,324
# DevTools 2.13.1 release notes The 2.13.1 release of the Dart and Flutter DevTools includes the following changes among other general improvements. To learn more about DevTools, check out the [DevTools overview](https://docs.flutter.dev/tools/devtools/overview). ## General updates * This release included a lot of cleanup and reduction in technical debt. The most notable is the completion of our migration to sound null safety. * Show release notes in IDE embedded versions of DevTools - [#4053](https://github.com/flutter/devtools/pull/4053) * Polish to the DevTools footer - [#3989](https://github.com/flutter/devtools/pull/3989), [#4026](https://github.com/flutter/devtools/pull/4026), [#4041](https://github.com/flutter/devtools/pull/4041), [#4076](https://github.com/flutter/devtools/pull/4076) ## Performance updates * Added a new feature to help you debug raster jank in your Flutter app. This feature allows you to take a snapshot of the current screen shown in your app, and then break down rendering time for that scene by layer. This can help you identify parts of a scene that are expensive to rasterize - [#4046](https://github.com/flutter/devtools/pull/4046) ![raster-metrics-feature](/tools/devtools/release-notes/images-2.13.1/image1.png "raster metrics feature") * Added a scope setting for "Track Widget Builds", allowing you to specify whether widget builds should be tracked in your code only or in all code - [#4010](https://github.com/flutter/devtools/pull/4010) ![track-widget-builds-scope-setting](/tools/devtools/release-notes/images-2.13.1/image2.png "track widget builds scope setting") ## CPU profiler updates * Use package uris instead of file uris in the CPU profiler "Source" column - [#3932](https://github.com/flutter/devtools/pull/3932) ## Debugger updates * Fix scrolling bug with debugger breakpoints - [#4074](https://github.com/flutter/devtools/pull/4074) ## Flutter inspector updates * Add support for displaying flex values larger than 5 in the Layout Explorer - [#4055](https://github.com/flutter/devtools/pull/4055) ## Full commit history To find a complete list of changes since the previous release, check out [the diff on GitHub](https://github.com/flutter/devtools/compare/v2.12.2...v2.13.1).
website/src/tools/devtools/release-notes/release-notes-2.13.1-src.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.13.1-src.md", "repo_id": "website", "token_count": 703 }
1,325
# DevTools 2.21.1 release notes The 2.21.1 release of the Dart and Flutter DevTools includes the following changes among other general improvements. To learn more about DevTools, check out the [DevTools overview](https://docs.flutter.dev/tools/devtools/overview). ## Performance updates * Replace the DevTools timeline trace viewer with the [Perfetto](https://perfetto.dev/) trace viewer - [#5142](https://github.com/flutter/devtools/pull/5142) ![perfetto trace viewer](/tools/devtools/release-notes/images-2.21.1/image1.png "perfetto_trace_viewer") * Fix several issues with loading a Performance snapshot into DevTools - [#5048](https://github.com/flutter/devtools/pull/5048), [#4929](https://github.com/flutter/devtools/pull/4929) * UI polish and cleanup - [#4889](https://github.com/flutter/devtools/pull/4889) ## Memory updates * Improve usability of snapshot diffing - [#5015](https://github.com/flutter/devtools/pull/5015) * UI polish and cleanup - [#4855](https://github.com/flutter/devtools/pull/4855) * Color code classes based on where they are defined (SDK, your package, dependencies, etc.) - [#5030](https://github.com/flutter/devtools/pull/5030) * Fix state management issue for tracing - [#5062](https://github.com/flutter/devtools/pull/5062) * Improve the performance of taking a heap snapshot - [#5134](https://github.com/flutter/devtools/pull/5134) * Retire broken import/export feature - [#5135](https://github.com/flutter/devtools/pull/5135) ## Debugger updates * Added support for viewing profiler hits in the debugger script viewer - [#4831](https://github.com/flutter/devtools/pull/4831) * Added support for inspecting records - [#5084](https://github.com/flutter/devtools/pull/5084) ## General updates * Fix several issues in syntax highlighting that would color variable names that contain reserved words incorrectly and leave `extends`/`implements` clauses uncolored for some classes - [#4948](https://github.com/flutter/devtools/pull/4948) * Fix an issue in Safari, and other browsers that do not support RegExp negative lookbehind, that prevented DevTools from loading - [#4938](https://github.com/flutter/devtools/pull/4938) * Fix an issue that would prevent DevTools connecting to the backend server that would disable some functionality - [#5016](https://github.com/flutter/devtools/pull/5016) * Add a link to the DevTools [contribution guide](https://github.com/flutter/devtools/blob/master/CONTRIBUTING.md) to the About menu, and fixed the Discord link - [#4926](https://github.com/flutter/devtools/pull/4926) * Fix conflicting colors in light theme - [#5067](https://github.com/flutter/devtools/pull/5067) ## Full commit history To find a complete list of changes since the previous release, check out [the diff on GitHub](https://github.com/flutter/devtools/compare/v2.20.0...v2.21.1).
website/src/tools/devtools/release-notes/release-notes-2.21.1-src.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.21.1-src.md", "repo_id": "website", "token_count": 911 }
1,326
# DevTools 2.28.2 release notes The 2.28.2 release of the Dart and Flutter DevTools includes the following changes among other general improvements. To learn more about DevTools, check out the [DevTools overview](https://docs.flutter.dev/tools/devtools/overview). This was a cherry-pick release on top of DevTools 2.28.1. To learn about the improvements included in DevTools 2.28.1, please read the [release notes](/tools/devtools/release-notes/release-notes-2.28.1). ## DevTools Extension updates * Enabled DevTools extensions when debugging a Dart entry point that is not under `lib` (e.g. a unit test or integration test). Thanks to [@bartekpacia](https://github.com/bartekpacia) for this change! - [#6644](https://github.com/flutter/devtools/pull/6644) ## Full commit history To find a complete list of changes in this release, check out the [DevTools git log](https://github.com/flutter/devtools/tree/v2.28.2).
website/src/tools/devtools/release-notes/release-notes-2.28.2-src.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.28.2-src.md", "repo_id": "website", "token_count": 278 }
1,327
# DevTools 2.33.0 release notes The 2.33.0 release of the Dart and Flutter DevTools includes the following changes among other general improvements. To learn more about DevTools, check out the [DevTools overview](/tools/devtools/overview). ## General updates * Improved overall usability by making the DevTools UI more dense. This significantly improves the user experience when using DevTools embedded in an IDE. - [#7030](https://github.com/flutter/devtools/pull/7030) * Removed the "Dense mode" setting. - [#7086](https://github.com/flutter/devtools/pull/7086) * Added support for filtering with regular expressions in the Logging, Network, and CPU profiler pages. - [#7027](https://github.com/flutter/devtools/pull/7027) * Add a DevTools server interaction for getting the DTD URI. - [#7054](https://github.com/flutter/devtools/pull/7054), [#7164](https://github.com/flutter/devtools/pull/7164) * Enabled expression evaluation with scope for the web, allowing evaluation of inspected widgets. - [#7144](https://github.com/flutter/devtools/pull/7144) * Update `package:vm_service` constraint to `^14.0.0`. - [#6953](https://github.com/flutter/devtools/pull/6953) * Onboarding DevTools to [`package:unified_analytics`](https://pub.dev/packages/unified_analytics) for unified telemetry logging across Flutter and Dart tooling. - [#7084](https://github.com/flutter/devtools/pull/7084) ## Debugger updates * Fixed off by one error causing profiler hits to be rendered on the wrong lines. - [#7178](https://github.com/flutter/devtools/pull/7178) * Improved contrast of line numbers when displaying code coverage hits in dark mode. - [#7178](https://github.com/flutter/devtools/pull/7178) * Improved contrast of profiling details when displaying profiler hits in dark mode. - [#7178](https://github.com/flutter/devtools/pull/7178) * Fixed syntax highlighting for comments when the source file uses `\r\n` line endings [#7190](https://github.com/flutter/devtools/pull/7190) * Re-establish breakpoints after a hot-restart. - [#7205](https://github.com/flutter/devtools/pull/7205) ## VS Code Sidebar updates * Do not show DevTools release notes in the Flutter sidebar. - [#7166](https://github.com/flutter/devtools/pull/7166) ## DevTools Extension updates * Added support for connecting to the Dart Tooling Daemon from the simulated DevTools environment. - [#7133](https://github.com/flutter/devtools/pull/7133) * Added help buttons to the VM Service and DTD connection text fields in the simulated DevTools environment. - [#7133](https://github.com/flutter/devtools/pull/7133) * Fixed an issue with not detecting extensions for test files in subdirectories. - [#7174](https://github.com/flutter/devtools/pull/7174) * Added an example of creating an extension for a pure Dart package. - [#7196](https://github.com/flutter/devtools/pull/7196) * Updated the `README.md` and `example/README.md` with more complete documentation. - [#7237](https://github.com/flutter/devtools/pull/7237), [#7261](https://github.com/flutter/devtools/pull/7261) * Added a `devtools_extensions validate` command to validate extension requirements during development. - [#7257](https://github.com/flutter/devtools/pull/7257) ## Full commit history To find a complete list of changes in this release, check out the [DevTools git log](https://github.com/flutter/devtools/tree/v2.33.0).
website/src/tools/devtools/release-notes/release-notes-2.33.0-src.md/0
{ "file_path": "website/src/tools/devtools/release-notes/release-notes-2.33.0-src.md", "repo_id": "website", "token_count": 1014 }
1,328
--- title: "Flutter and the pubspec file" description: "Describes the Flutter-only fields in the pubspec file." --- {{site.alert.note}} This page is primarily aimed at folks who write Flutter apps. If you write packages or plugins, (perhaps you want to create a federated plugin), you should check out the [Developing packages and plugins][] page. {{site.alert.end}} Every Flutter project includes a `pubspec.yaml` file, often referred to as _the pubspec_. A basic pubspec is generated when you create a new Flutter project. It's located at the top of the project tree and contains metadata about the project that the Dart and Flutter tooling needs to know. The pubspec is written in [YAML][], which is human readable, but be aware that _white space (tabs v spaces) matters_. [YAML]: https://yaml.org/ The pubspec file specifies dependencies that the project requires, such as particular packages (and their versions), fonts, or image files. It also specifies other requirements, such as dependencies on developer packages (like testing or mocking packages), or particular constraints on the version of the Flutter SDK. Fields common to both Dart and Flutter projects are described in [the pubspec file][] on [dart.dev][]. This page lists _Flutter-specific_ fields that are only valid for a Flutter project. {{site.alert.note}} The first time you build your project, it creates a `pubspec.lock` file that contains specific versions of the included packages. This ensures that you get the same version the next time the project is built. {{site.alert.end}} [the pubspec file]: {{site.dart-site}}/tools/pub/pubspec [dart.dev]: {{site.dart-site}} When you create a new project with the `flutter create` command (or by using the equivalent button in your IDE), it creates a pubspec for a basic Flutter app. Here is an example of a Flutter project pubspec file. The Flutter only fields are highlighted. {% prettify yaml %} name: <project name> description: A new Flutter project. publish_to: none version: 1.0.0+1 environment: sdk: ^3.3.0 dependencies: [[highlight]]flutter:[[/highlight]] # Required for every Flutter project [[highlight]]sdk: flutter[[/highlight]] # Required for every Flutter project [[highlight]]flutter_localizations:[[/highlight]] # Required to enable localization [[highlight]]sdk: flutter[[/highlight]] # Required to enable localization [[highlight]]cupertino_icons: ^1.0.6[[/highlight]] # Only required if you use Cupertino (iOS style) icons dev_dependencies: [[highlight]]flutter_test:[[/highlight]] [[highlight]]sdk: flutter[[/highlight]] # Required for a Flutter project that includes tests [[highlight]]flutter_lints: ^3.0.1[[/highlight]] # Contains a set of recommended lints for Flutter code [[highlight]]flutter:[[/highlight]] [[highlight]]uses-material-design: true[[/highlight]] # Required if you use the Material icon font [[highlight]]generate: true[[/highlight]] # Enables generation of localized strings from arb files [[highlight]]assets:[[/highlight]] # Lists assets, such as image files [[highlight]]- images/a_dot_burr.jpeg[[/highlight]] [[highlight]]- images/a_dot_ham.jpeg[[/highlight]] [[highlight]]fonts:[[/highlight]] # Required if your app uses custom fonts [[highlight]]- family: Schyler[[/highlight]] [[highlight]]fonts:[[/highlight]] [[highlight]]- asset: fonts/Schyler-Regular.ttf[[/highlight]] [[highlight]]- asset: fonts/Schyler-Italic.ttf[[/highlight]] [[highlight]]style: italic[[/highlight]] [[highlight]]- family: Trajan Pro[[/highlight]] [[highlight]]fonts:[[/highlight]] [[highlight]]- asset: fonts/TrajanPro.ttf[[/highlight]] [[highlight]]- asset: fonts/TrajanPro_Bold.ttf[[/highlight]] [[highlight]]weight: 700[[/highlight]] {% endprettify %} ## Assets Common types of assets include static data (for example, JSON files), configuration files, icons, and images (JPEG, WebP, GIF, animated WebP/GIF, PNG, BMP, and WBMP). Besides listing the images that are included in the app package, an image asset can also refer to one or more resolution-specific "variants". For more information, see the [resolution aware][] section of the [Assets and images][] page. For information on adding assets from package dependencies, see the [asset images in package dependencies][] section in the same page. [Assets and images]: /ui/assets/assets-and-images [asset images in package dependencies]: /ui/assets/assets-and-images#from-packages [resolution aware]: /ui/assets/assets-and-images#resolution-aware ## Fonts As shown in the above example, each entry in the fonts section should have a `family` key with the font family name, and a `fonts` key with a list specifying the asset and other descriptors for the font. For examples of using fonts see the [Use a custom font][] and [Export fonts from a package][] recipes in the [Flutter cookbook][]. [Export fonts from a package]: /cookbook/design/package-fonts [Flutter cookbook]: /cookbook [Use a custom font]: /cookbook/design/fonts ## More information For more information on packages, plugins, and pubspec files, see the following: * [Creating packages][] on dart.dev * [Glossary of package terms][] on dart.dev * [Package dependencies][] on dart.dev * [Using packages][] * [What not to commit][] on dart.dev [Creating packages]: {{site.dart-site}}/guides/libraries/create-library-packages [Developing packages and plugins]: /packages-and-plugins/developing-packages [Federated plugins]: /packages-and-plugins/developing-packages#federated-plugins [Glossary of package terms]: {{site.dart-site}}/tools/pub/glossary [Package dependencies]: {{site.dart-site}}/tools/pub/dependencies [Using packages]: /packages-and-plugins/using-packages [What not to commit]: {{site.dart-site}}/guides/libraries/private-files#pubspeclock
website/src/tools/pubspec.md/0
{ "file_path": "website/src/tools/pubspec.md", "repo_id": "website", "token_count": 1824 }
1,329
--- layout: toc title: Custom drawing and graphics short-title: Drawing & graphics description: > Content covering how to create custom graphics and use your own shaders in Flutter apps. sitemap: false ---
website/src/ui/design/graphics/index.md/0
{ "file_path": "website/src/ui/design/graphics/index.md", "repo_id": "website", "token_count": 57 }
1,330
--- title: Building adaptive apps description: Some considerations and instructions on how to build adaptive apps to run on a variety of platforms. --- <?code-excerpt path-base="ui/layout/adaptive_app_demos"?> ## Overview Flutter provides new opportunities to build apps that can run on mobile, desktop, and the web from a single codebase. However, with these opportunities, come new challenges. You want your app to feel familiar to users, adapting to each platform by maximizing usability and ensuring a comfortable and seamless experience. That is, you need to build apps that are not just multiplatform, but are fully platform adaptive. There are many considerations for developing platform-adaptive apps, but they fall into three major categories: * [Layout](#building-adaptive-layouts) * [Input](#input) * [Idioms and norms](#idioms-and-norms) <iframe style="max-width: 100%" width="560" height="315" src="{{site.yt.embed}}/RCdeSKVt7LI" title="Learn how to build platform-adaptive Flutter apps" {{site.yt.set}}></iframe> This page covers all three categories in detail using code snippets to illustrate the concepts. If you'd like to see how these concepts come together, check out the [Flokk][] and [Folio][] examples that were built using the concepts described here. [Flokk]: {{site.github}}/gskinnerTeam/flokk [Folio]: {{site.github}}/gskinnerTeam/flutter-folio Original demo code for adaptive app development techniques from [flutter-adaptive-demo](https://github.com/gskinnerTeam/flutter-adaptive-demo). ## Building adaptive layouts One of the first things you must consider when writing your app for multiple platforms is how to adapt it to the various sizes and shapes of the screens that it will run on. ### Layout widgets If you've been building apps or websites, you're probably familiar with creating responsive interfaces. Luckily for Flutter developers, there are a large set of widgets to make this easier. Some of Flutter's most useful layout widgets include: **Single child** * [`Align`][]&mdash;Aligns a child within itself. It takes a double value between -1 and 1, for both the vertical and horizontal alignment. * [`AspectRatio`][]&mdash;Attempts to size the child to a specific aspect ratio. * [`ConstrainedBox`][]&mdash;Imposes size constraints on its child, offering control over the minimum or maximum size. * [`CustomSingleChildLayout`][]&mdash;Uses a delegate function to position a single child. The delegate can determine the layout constraints and positioning for the child. * [`Expanded`][] and [`Flexible`][]&mdash;Allows a child of a `Row` or `Column` to shrink or grow to fill any available space. * [`FractionallySizedBox`][]&mdash;Sizes its child to a fraction of the available space. * [`LayoutBuilder`][]&mdash;Builds a widget that can reflow itself based on its parents size. * [`SingleChildScrollView`][]&mdash;Adds scrolling to a single child. Often used with a `Row` or `Column`. **Multichild** * [`Column`][], [`Row`][], and [`Flex`][]&mdash;Lays out children in a single horizontal or vertical run. Both `Column` and `Row` extend the `Flex` widget. * [`CustomMultiChildLayout`][]&mdash;Uses a delegate function to position multiple children during the layout phase. * [`Flow`][]&mdash;Similar to `CustomMultiChildLayout`, but more efficient because it's performed during the paint phase rather than the layout phase. * [`ListView`][], [`GridView`][], and [`CustomScrollView`][]&mdash;Provides scrollable lists of children. * [`Stack`][]&mdash;Layers and positions multiple children relative to the edges of the `Stack`. Functions similarly to position-fixed in CSS. * [`Table`][]&mdash;Uses a classic table layout algorithm for its children, combining multiple rows and columns. * [`Wrap`][]&mdash;Displays its children in multiple horizontal or vertical runs. To see more available widgets and example code, see [Layout widgets][]. [`Align`]: {{site.api}}/flutter/widgets/Align-class.html [`AspectRatio`]: {{site.api}}/flutter/widgets/AspectRatio-class.html [`Column`]: {{site.api}}/flutter/widgets/Column-class.html [`ConstrainedBox`]: {{site.api}}/flutter/widgets/ConstrainedBox-class.html [`CustomMultiChildLayout`]: {{site.api}}/flutter/widgets/CustomMultiChildLayout-class.html [`CustomScrollView`]: {{site.api}}/flutter/widgets/CustomScrollView-class.html [`CustomSingleChildLayout`]: {{site.api}}/flutter/widgets/CustomSingleChildLayout-class.html [`Expanded`]: {{site.api}}/flutter/widgets/Expanded-class.html [`Flex`]: {{site.api}}/flutter/widgets/Flex-class.html [`Flexible`]: {{site.api}}/flutter/widgets/Flexible-class.html [`Flow`]: {{site.api}}/flutter/widgets/Flow-class.html [`FractionallySizedBox`]: {{site.api}}/flutter/widgets/FractionallySizedBox-class.html [`GridView`]: {{site.api}}/flutter/widgets/GridView-class.html [Layout widgets]: /ui/widgets/layout [`LayoutBuilder`]: {{site.api}}/flutter/widgets/LayoutBuilder-class.html [`ListView`]: {{site.api}}/flutter/widgets/ListView-class.html [`Row`]: {{site.api}}/flutter/widgets/Row-class.html [`SingleChildScrollView`]: {{site.api}}/flutter/widgets/SingleChildScrollView-class.html [`Stack`]: {{site.api}}/flutter/widgets/Stack-class.html [`Table`]: {{site.api}}/flutter/widgets/Table-class.html [`Wrap`]: {{site.api}}/flutter/widgets/Wrap-class.html ### Visual density Different input devices offer various levels of precision, which necessitate differently sized hit areas. Flutter's `VisualDensity` class makes it easy to adjust the density of your views across the entire application, for example, by making a button larger (and therefore easier to tap) on a touch device. When you change the `VisualDensity` for your `MaterialApp`, `MaterialComponents` that support it animate their densities to match. By default, both horizontal and vertical densities are set to 0.0, but you can set the densities to any negative or positive value that you want. By switching between different densities, you can easily adjust your UI: ![Adaptive scaffold](/assets/images/docs/development/ui/layout/adaptive_scaffold.gif){:width="100%"} To set a custom visual density, inject the density into your `MaterialApp` theme: <?code-excerpt "lib/main.dart (VisualDensity)"?> ```dart double densityAmt = touchMode ? 0.0 : -1.0; VisualDensity density = VisualDensity(horizontal: densityAmt, vertical: densityAmt); return MaterialApp( theme: ThemeData(visualDensity: density), home: MainAppScaffold(), debugShowCheckedModeBanner: false, ); ``` To use `VisualDensity` inside your own views, you can look it up: <?code-excerpt "lib/pages/adaptive_reflow_page.dart (VisualDensityOwnView)"?> ```dart VisualDensity density = Theme.of(context).visualDensity; ``` Not only does the container react automatically to changes in density, it also animates when it changes. This ties together your custom components, along with the built-in components, for a smooth transition effect across the app. As shown, `VisualDensity` is unit-less, so it can mean different things to different views. In this example, 1 density unit equals 6 pixels, but this is totally up to your views to decide. The fact that it is unit-less makes it quite versatile, and it should work in most contexts. It's worth noting that the Material Components generally use a value of around 4 logical pixels for each visual density unit. For more information about the supported components, see [`VisualDensity`][] API. For more information about density principles in general, see the [Material Design guide][]. [Material Design guide]: {{site.material2}}/design/layout/applying-density.html#usage [`VisualDensity`]: {{site.api}}/flutter/material/VisualDensity-class.html ### Contextual layout If you need more than density changes and can't find a widget that does what you need, you can take a more procedural approach to adjust parameters, calculate sizes, swap widgets, or completely restructure your UI to suit a particular form factor. #### Screen-based breakpoints The simplest form of procedural layouts uses screen-based breakpoints. In Flutter, this can be done with the `MediaQuery` API. There are no hard and fast rules for the sizes to use here, but these are general values: <?code-excerpt "lib/global/device_size.dart (FormFactor)"?> ```dart class FormFactor { static double desktop = 900; static double tablet = 600; static double handset = 300; } ``` Using breakpoints, you can set up a simple system to determine the device type: <?code-excerpt "lib/global/device_size.dart (getFormFactor)"?> ```dart ScreenType getFormFactor(BuildContext context) { // Use .shortestSide to detect device type regardless of orientation double deviceWidth = MediaQuery.of(context).size.shortestSide; if (deviceWidth > FormFactor.desktop) return ScreenType.desktop; if (deviceWidth > FormFactor.tablet) return ScreenType.tablet; if (deviceWidth > FormFactor.handset) return ScreenType.handset; return ScreenType.watch; } ``` As an alternative, you could abstract it more and define it in terms of small to large: <?code-excerpt "lib/global/device_size.dart (ScreenSize)"?> ```dart enum ScreenSize { small, normal, large, extraLarge } ScreenSize getSize(BuildContext context) { double deviceWidth = MediaQuery.of(context).size.shortestSide; if (deviceWidth > 900) return ScreenSize.extraLarge; if (deviceWidth > 600) return ScreenSize.large; if (deviceWidth > 300) return ScreenSize.normal; return ScreenSize.small; } ``` Screen-based breakpoints are best used for making top-level decisions in your app. Changing things like visual density, paddings, or font-sizes are best when defined on a global basis. You can also use screen-based breakpoints to reflow your top-level widget trees. For example, you could switch from a vertical to a horizontal layout when the user isn't on a handset: <?code-excerpt "lib/global/device_size.dart (MediaQuery)"?> ```dart bool isHandset = MediaQuery.of(context).size.width < 600; return Flex( direction: isHandset ? Axis.vertical : Axis.horizontal, children: const [Text('Foo'), Text('Bar'), Text('Baz')], ); ``` In another widget, you might swap some of the children completely: <?code-excerpt "lib/global/device_size.dart (WidgetSwap)"?> ```dart Widget foo = Row( children: [ ...isHandset ? _getHandsetChildren() : _getNormalChildren(), ], ); ``` #### Use LayoutBuilder for extra flexibility Even though checking total screen size is great for full-screen pages or making global layout decisions, it's often not ideal for nested subviews. Often, subviews have their own internal breakpoints and care only about the space that they have available to render. The simplest way to handle this in Flutter is using the [`LayoutBuilder`][] class. `LayoutBuilder` allows a widget to respond to incoming local size constraints, which can make the widget more versatile than if it depended on a global value. The previous example could be rewritten using `LayoutBuilder`: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (LayoutBuilder)"?> ```dart Widget foo = LayoutBuilder(builder: (context, constraints) { bool useVerticalLayout = constraints.maxWidth < 400; return Flex( direction: useVerticalLayout ? Axis.vertical : Axis.horizontal, children: const [ Text('Hello'), Text('World'), ], ); }); ``` This widget can now be composed within a side panel, dialog, or even a full-screen view, and adapt its layout to whatever space is provided. #### Device segmentation There are times when you want to make layout decisions based on the actual platform you're running on, regardless of size. For example, when building a custom title bar, you might need to check the operating system type and tweak the layout of your title bar, so it doesn't get covered by the native window buttons. To determine which combination of platforms you're on, you can use the [`Platform`][] API along with the `kIsWeb` value: <?code-excerpt "lib/global/device_type.dart (Platforms)"?> ```dart bool get isMobileDevice => !kIsWeb && (Platform.isIOS || Platform.isAndroid); bool get isDesktopDevice => !kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux); bool get isMobileDeviceOrWeb => kIsWeb || isMobileDevice; bool get isDesktopDeviceOrWeb => kIsWeb || isDesktopDevice; ``` The `Platform` API can't be accessed from web builds without throwing an exception, because the `dart.io` package isn't supported on the web target. As a result, the above code checks for web first, and because of short-circuiting, Dart never calls `Platform` on web targets. Use `Platform`/`kIsWeb` when the logic absolutely <i>must</i> run for a given platform. For example, talking to a plugin that only works on iOS, or displaying a widget that only conforms to Play Store policy and not the App Store's. [`Platform`]: {{site.api}}/flutter/package-platform_platform/Platform-class.html ### Single source of truth for styling You'll probably find it easier to maintain your views if you create a single source of truth for styling values like padding, spacing, corner shape, font sizes, and so on. This can be done easily with some helper classes: <?code-excerpt "lib/global/device_type.dart (Styling)"?> ```dart class Insets { static const double xsmall = 3; static const double small = 4; static const double medium = 5; static const double large = 10; static const double extraLarge = 20; // etc } class Fonts { static const String raleway = 'Raleway'; // etc } class TextStyles { static const TextStyle raleway = TextStyle( fontFamily: Fonts.raleway, ); static TextStyle buttonText1 = const TextStyle(fontWeight: FontWeight.bold, fontSize: 14); static TextStyle buttonText2 = const TextStyle(fontWeight: FontWeight.normal, fontSize: 11); static TextStyle h1 = const TextStyle(fontWeight: FontWeight.bold, fontSize: 22); static TextStyle h2 = const TextStyle(fontWeight: FontWeight.bold, fontSize: 16); static TextStyle body1 = raleway.copyWith(color: const Color(0xFF42A5F5)); // etc } ``` These constants can then be used in place of hard-coded numeric values: <?code-excerpt "lib/global/device_type.dart (UseConstants)"?> ```dart return Padding( padding: const EdgeInsets.all(Insets.small), child: Text('Hello!', style: TextStyles.body1), ); ``` Use `Theme.of(context).platform` for theming and design choices, like what kind of switches to show and general Cupertino/Material adaptions. With all views referencing the same shared-design system rules, they tend to look better and more consistent. Making a change or adjusting a value for a specific platform can be done in a single place, instead of using an error-prone search and replace. Using shared rules has the added benefit of helping enforce consistency on the design side. Some common design system categories that can be represented this way are: * Animation timings * Sizes and breakpoints * Insets and paddings * Corner radius * Shadows * Strokes * Font families, sizes, and styles Like most rules, there are exceptions: one-off values that are used nowhere else in the app. There is little point in cluttering up the styling rules with these values, but it's worth considering if they should be derived from an existing value (for example, `padding + 1.0`). You should also watch for reuse or duplication of the same semantic values. Those values should likely be added to the global styling ruleset. ### Design to the strengths of each form factor Beyond screen size, you should also spend time considering the unique strengths and weaknesses of different form factors. It isn't always ideal for your multiplatform app to offer identical functionality everywhere. Consider whether it makes sense to focus on specific capabilities, or even remove certain features, on some device categories. For example, mobile devices are portable and have cameras, but they aren't well suited for detailed creative work. With this in mind, you might focus more on capturing content and tagging it with location data for a mobile UI, but focus on organizing or manipulating that content for a tablet or desktop UI. Another example is leveraging the web's extremely low barrier for sharing. If you're deploying a web app, decide which deep links to support, and design your navigation routes with those in mind. The key takeaway here is to think about what each platform does best and see if there are unique capabilities you can leverage. ### Use desktop build targets for rapid testing One of the most effective ways to test adaptive interfaces is to take advantage of the desktop build targets. When running on a desktop, you can easily resize the window while the app is running to preview various screen sizes. This, combined with hot reload, can greatly accelerate the development of a responsive UI. ![Adaptive scaffold 2](/assets/images/docs/development/ui/layout/adaptive_scaffold2.gif){:width="100%"} ### Solve touch first Building a great touch UI can often be more difficult than a traditional desktop UI due, in part, to the lack of input accelerators like right-click, scroll wheel, or keyboard shortcuts. One way to approach this challenge is to focus initially on a great touch-oriented UI. You can still do most of your testing using the desktop target for its iteration speed. But, remember to switch frequently to a mobile device to verify that everything feels right. After you have the touch interface polished, you can tweak the visual density for mouse users, and then layer on all the additional inputs. Approach these other inputs as accelerator—alternatives that make a task faster. The important thing to consider is what a user expects when using a particular input device, and work to reflect that in your app. ## Input Of course, it isn't enough to just adapt how your app looks, you also have to support varying user inputs. The mouse and keyboard introduce input types beyond those found on a touch device—like scroll wheel, right-click, hover interactions, tab traversal, and keyboard shortcuts. ### Scroll wheel Scrolling widgets like `ScrollView` or `ListView` support the scroll wheel by default, and because almost every scrollable custom widget is built using one of these, it works with them as well. If you need to implement custom scroll behavior, you can use the [`Listener`][] widget, which lets you customize how your UI reacts to the scroll wheel. <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (PointerScroll)"?> ```dart return Listener( onPointerSignal: (event) { if (event is PointerScrollEvent) print(event.scrollDelta.dy); }, child: ListView(), ); ``` [`Listener`]: {{site.api}}/flutter/widgets/Listener-class.html ### Tab traversal and focus interactions Users with physical keyboards expect that they can use the tab key to quickly navigate your application, and users with motor or vision differences often rely completely on keyboard navigation. There are two considerations for tab interactions: how focus moves from widget to widget, known as traversal, and the visual highlight shown when a widget is focused. Most built-in components, like buttons and text fields, support traversal and highlights by default. If you have your own widget that you want included in traversal, you can use the [`FocusableActionDetector`][] widget to create your own controls. It combines the functionality of [`Actions`][], [`Shortcuts`][], [`MouseRegion`][], and [`Focus`][] widgets to create a detector that defines actions and key bindings, and provides callbacks for handling focus and hover highlights. <?code-excerpt "lib/pages/focus_examples_page.dart (_BasicActionDetectorState)"?> ```dart class _BasicActionDetectorState extends State<BasicActionDetector> { bool _hasFocus = false; @override Widget build(BuildContext context) { return FocusableActionDetector( onFocusChange: (value) => setState(() => _hasFocus = value), actions: <Type, Action<Intent>>{ ActivateIntent: CallbackAction<Intent>(onInvoke: (intent) { print('Enter or Space was pressed!'); return null; }), }, child: Stack( clipBehavior: Clip.none, children: [ const FlutterLogo(size: 100), // Position focus in the negative margin for a cool effect if (_hasFocus) Positioned( left: -4, top: -4, bottom: -4, right: -4, child: _roundedBorder(), ) ], ), ); } } ``` [`Actions`]: {{site.api}}/flutter/widgets/Actions-class.html [`Focus`]: {{site.api}}/flutter/widgets/Focus-class.html [`FocusableActionDetector`]: {{site.api}}/flutter/widgets/FocusableActionDetector-class.html [`MouseRegion`]: {{site.api}}/flutter/widgets/MouseRegion-class.html [`Shortcuts`]: {{site.api}}/flutter/widgets/Shortcuts-class.html #### Controlling traversal order To get more control over the order that widgets are focused on when the user presses tab, you can use [`FocusTraversalGroup`][] to define sections of the tree that should be treated as a group when tabbing. For example, you might to tab through all the fields in a form before tabbing to the submit button: <?code-excerpt "lib/pages/focus_examples_page.dart (FocusTraversalGroup)"?> ```dart return Column(children: [ FocusTraversalGroup( child: MyFormWithMultipleColumnsAndRows(), ), SubmitButton(), ]); ``` Flutter has several built-in ways to traverse widgets and groups, defaulting to the `ReadingOrderTraversalPolicy` class. This class usually works well, but it's possible to modify this using another predefined `TraversalPolicy` class or by creating a custom policy. [`FocusTraversalGroup`]: {{site.api}}/flutter/widgets/FocusTraversalGroup-class.html ### Keyboard accelerators In addition to tab traversal, desktop and web users are accustomed to having various keyboard shortcuts bound to specific actions. Whether it's the `Delete` key for quick deletions or `Control+N` for a new document, be sure to consider the different accelerators your users expect. The keyboard is a powerful input tool, so try to squeeze as much efficiency from it as you can. Your users will appreciate it! Keyboard accelerators can be accomplished in a few ways in Flutter depending on your goals. If you have a single widget like a `TextField` or a `Button` that already has a focus node, you can wrap it in a [`KeyboardListener`][] or a [`Focus`][] widget and listen for keyboard events: <?code-excerpt "lib/pages/focus_examples_page.dart (focus-keyboard-listener)"?> ```dart @override Widget build(BuildContext context) { return Focus( onKeyEvent: (node, event) { if (event is KeyDownEvent) { print(event.logicalKey); } return KeyEventResult.ignored; }, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 400), child: const TextField( decoration: InputDecoration( border: OutlineInputBorder(), ), ), ), ); } } ``` If you'd like to apply a set of keyboard shortcuts to a large section of the tree, you can use the [`Shortcuts`][] widget: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (Shortcuts)"?> ```dart // Define a class for each type of shortcut action you want class CreateNewItemIntent extends Intent { const CreateNewItemIntent(); } Widget build(BuildContext context) { return Shortcuts( // Bind intents to key combinations shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyN, control: true): CreateNewItemIntent(), }, child: Actions( // Bind intents to an actual method in your code actions: <Type, Action<Intent>>{ CreateNewItemIntent: CallbackAction<CreateNewItemIntent>( onInvoke: (intent) => _createNewItem(), ), }, // Your sub-tree must be wrapped in a focusNode, so it can take focus. child: Focus( autofocus: true, child: Container(), ), ), ); } ``` The [`Shortcuts`][] widget is useful because it only allows shortcuts to be fired when this widget tree or one of its children has focus and is visible. The final option is a global listener. This listener can be used for always-on, app-wide shortcuts or for panels that can accept shortcuts whenever they're visible (regardless of their focus state). Adding global listeners is easy with [`HardwareKeyboard`][]: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (hardware-keyboard)"?> ```dart @override void initState() { super.initState(); HardwareKeyboard.instance.addHandler(_handleKey); } @override void dispose() { HardwareKeyboard.instance.removeHandler(_handleKey); super.dispose(); } ``` To check key combinations with the global listener, you can use the `HardwareKeyboard.instance.logicalKeysPressed` set. For example, a method like the following can check whether any of the provided keys are being held down: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (KeysPressed)"?> ```dart static bool isKeyDown(Set<LogicalKeyboardKey> keys) { return keys .intersection(HardwareKeyboard.instance.logicalKeysPressed) .isNotEmpty; } ``` Putting these two things together, you can fire an action when `Shift+N` is pressed: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (HandleKey)"?> ```dart bool _handleKey(KeyEvent event) { bool isShiftDown = isKeyDown({ LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight, }); if (isShiftDown && event.logicalKey == LogicalKeyboardKey.keyN) { _createNewItem(); return true; } return false; } ``` One note of caution when using the static listener, is that you often need to disable it when the user is typing in a field or when the widget it's associated with is hidden from view. Unlike with `Shortcuts` or `KeyboardListener`, this is your responsibility to manage. This can be especially important when you're binding a Delete/Backspace accelerator for `Delete`, but then have child `TextFields` that the user might be typing in. [`HardwareKeyboard`]: {{site.api}}/flutter/services/HardwareKeyboard-class.html [`KeyboardListener`]: {{site.api}}/flutter/widgets/KeyboardListener-class.html ### Mouse enter, exit, and hover On desktop, it's common to change the mouse cursor to indicate the functionality about the content the mouse is hovering over. For example, you usually see a hand cursor when you hover over a button, or an `I` cursor when you hover over text. The Material Component set has built-in support for your standard button and text cursors. To change the cursor from within your own widgets, use [`MouseRegion`][]: <?code-excerpt "lib/pages/focus_examples_page.dart (MouseRegion)"?> ```dart // Show hand cursor return MouseRegion( cursor: SystemMouseCursors.click, // Request focus when clicked child: GestureDetector( onTap: () { Focus.of(context).requestFocus(); _submit(); }, child: Logo(showBorder: hasFocus), ), ); ``` `MouseRegion` is also useful for creating custom rollover and hover effects: <?code-excerpt "lib/pages/focus_examples_page.dart (MouseOver)"?> ```dart return MouseRegion( onEnter: (_) => setState(() => _isMouseOver = true), onExit: (_) => setState(() => _isMouseOver = false), onHover: (e) => print(e.localPosition), child: Container( height: 500, color: _isMouseOver ? Colors.blue : Colors.black, ), ); ``` ## Idioms and norms The final area to consider for adaptive apps is platform standards. Each platform has its own idioms and norms; these nominal or de facto standards inform user expectations of how an application should behave. Thanks, in part to the web, users are accustomed to more customized experiences, but reflecting these platform standards can still provide significant benefits: * **Reduce cognitive load**&mdash;By matching the user's existing mental model, accomplishing tasks becomes intuitive, which requires less thinking, boosts productivity, and reduces frustrations. * **Build trust**&mdash;Users can become wary or suspicious when applications don't adhere to their expectations. Conversely, a UI that feels familiar can build user trust and can help improve the perception of quality. This often has the added benefit of better app store ratings&mdash;something we can all appreciate! ### Consider expected behavior on each platform The first step is to spend some time considering what the expected appearance, presentation, or behavior is on this platform. Try to forget any limitations of your current implementation, and just envision the ideal user experience. Work backwards from there. Another way to think about this is to ask, "How would a user of this platform expect to achieve this goal?" Then, try to envision how that would work in your app without any compromises. This can be difficult if you aren't a regular user of the platform. You might be unaware of the specific idioms and can easily miss them completely. For example, a lifetime Android user is likely unaware of platform conventions on iOS, and the same holds true for macOS, Linux, and Windows. These differences might be subtle to you, but be painfully obvious to an experienced user. #### Find a platform advocate If possible, assign someone as an advocate for each platform. Ideally, your advocate uses the platform as their primary device, and can offer the perspective of a highly opinionated user. To reduce the number of people, combine roles. Have one advocate for Windows and Android, one for Linux and the web, and one for Mac and iOS. The goal is to have constant, informed feedback so the app feels great on each platform. Advocates should be encouraged to be quite picky, calling out anything they feel differs from typical applications on their device. A simple example is how the default button in a dialog is typically on the left on Mac and Linux, but is on the right on Windows. Details like that are easy to miss if you aren't using a platform on a regular basis. {{site.alert.secondary}} **Important**: Advocates don't need to be developers or even full-time team members. They can be designers, stakeholders, or external testers that are provided with regular builds. {{site.alert.end}} #### Stay unique Conforming to expected behaviors doesn't mean that your app needs to use default components or styling. Many of the most popular multiplatform apps have very distinct and opinionated UIs including custom buttons, context menus, and title bars. The more you can consolidate styling and behavior across platforms, the easier development and testing will be. The trick is to balance creating a unique experience with a strong identity, while respecting the norms of each platform. ### Common idioms and norms to consider Take a quick look at a few specific norms and idioms you might want to consider, and how you could approach them in Flutter. #### Scrollbar appearance and behavior Desktop and mobile users expect scrollbars, but they expect them to behave differently on different platforms. Mobile users expect smaller scrollbars that only appear while scrolling, whereas desktop users generally expect omnipresent, larger scrollbars that they can click or drag. Flutter comes with a built-in `Scrollbar` widget that already has support for adaptive colors and sizes according to the current platform. The one tweak you might want to make is to toggle `alwaysShown` when on a desktop platform: <?code-excerpt "lib/pages/adaptive_grid_page.dart (ScrollbarAlwaysShown)"?> ```dart return Scrollbar( thumbVisibility: DeviceType.isDesktop, controller: _scrollController, child: GridView.count( controller: _scrollController, padding: const EdgeInsets.all(Insets.extraLarge), childAspectRatio: 1, crossAxisCount: colCount, children: listChildren, ), ); ``` This subtle attention to detail can make your app feel more comfortable on a given platform. #### Multi-select Dealing with multi-select within a list is another area with subtle differences across platforms: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (MultiSelectShift)"?> ```dart static bool get isSpanSelectModifierDown => isKeyDown({LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight}); ``` To perform a platform-aware check for control or command, you can write something like this: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (MultiSelectModifierDown)"?> ```dart static bool get isMultiSelectModifierDown { bool isDown = false; if (Platform.isMacOS) { isDown = isKeyDown( {LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight}, ); } else { isDown = isKeyDown( {LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlRight}, ); } return isDown; } ``` A final consideration for keyboard users is the **Select All** action. If you have a large list of items of selectable items, many of your keyboard users will expect that they can use `Control+A` to select all the items. ##### Touch devices On touch devices, multi-selection is typically simplified, with the expected behavior being similar to having the `isMultiSelectModifier` down on the desktop. You can select or deselect items using a single tap, and will usually have a button to **Select All** or **Clear** the current selection. How you handle multi-selection on different devices depends on your specific use cases, but the important thing is to make sure that you're offering each platform the best interaction model possible. #### Selectable text A common expectation on the web (and to a lesser extent desktop) is that most visible text can be selected with the mouse cursor. When text is not selectable, users on the web tend to have an adverse reaction. Luckily, this is easy to support with the [`SelectableText`][] widget: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (SelectableText)"?> ```dart return const SelectableText('Select me!'); ``` To support rich text, then use `TextSpan`: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (RichTextSpan)"?> ```dart return const SelectableText.rich( TextSpan( children: [ TextSpan(text: 'Hello'), TextSpan(text: 'Bold', style: TextStyle(fontWeight: FontWeight.bold)), ], ), ); ``` [`SelectableText`]: {{site.api}}/flutter/material/SelectableText-class.html #### Title bars On modern desktop applications, it's common to customize the title bar of your app window, adding a logo for stronger branding or contextual controls to help save vertical space in your main UI. ![Samples of title bars](/assets/images/docs/development/ui/layout/titlebar.png){:width="100%"} This isn't supported directly in Flutter, but you can use the [`bits_dojo`][] package to disable the native title bars, and replace them with your own. This package lets you add whatever widgets you want to the `TitleBar` because it uses pure Flutter widgets under the hood. This makes it easy to adapt the title bar as you navigate to different sections of the app. [`bits_dojo`]: {{site.github}}/bitsdojo/bitsdojo_window #### Context menus and tooltips On desktop, there are several interactions that manifest as a widget shown in an overlay, but with differences in how they're triggered, dismissed, and positioned: * **Context menu**&mdash;Typically triggered by a right-click, a context menu is positioned close to the mouse, and is dismissed by clicking anywhere, selecting an option from the menu, or clicking outside it. * **Tooltip**&mdash;Typically triggered by hovering for 200-400ms over an interactive element, a tooltip is usually anchored to a widget (as opposed to the mouse position) and is dismissed when the mouse cursor leaves that widget. * **Popup panel (also known as flyout)**&mdash;Similar to a tooltip, a popup panel is usually anchored to a widget. The main difference is that panels are most often shown on a tap event, and they usually don't hide themselves when the cursor leaves. Instead, panels are typically dismissed by clicking outside the panel or by pressing a **Close** or **Submit** button. To show basic tooltips in Flutter, use the built-in [`Tooltip`][] widget: <?code-excerpt "lib/widgets/extra_widget_excerpts.dart (Tooltip)"?> ```dart return const Tooltip( message: 'I am a Tooltip', child: Text('Hover over the text to show a tooltip.'), ); ``` Flutter also provides built-in context menus when editing or selecting text. To show more advanced tooltips, popup panels, or create custom context menus, you either use one of the available packages, or build it yourself using a `Stack` or `Overlay`. Some available packages include: * [`context_menus`][] * [`anchored_popups`][] * [`flutter_portal`][] * [`super_tooltip`][] * [`custom_pop_up_menu`][] While these controls can be valuable for touch users as accelerators, they are essential for mouse users. These users expect to right-click things, edit content in place, and hover for more information. Failing to meet those expectations can lead to disappointed users, or at least, a feeling that something isn't quite right. [`anchored_popups`]: {{site.pub}}/packages/anchored_popups [`context_menus`]: {{site.pub}}/packages/context_menus [`custom_pop_up_menu`]: {{site.pub}}/packages/custom_pop_up_menu [`flutter_portal`]: {{site.pub}}/packages/flutter_portal [`super_tooltip`]: {{site.pub}}/packages/super_tooltip [`Tooltip`]: {{site.api}}/flutter/material/Tooltip-class.html #### Horizontal button order On Windows, when presenting a row of buttons, the confirmation button is placed at the start of the row (left side). On all other platforms, it's the opposite. The confirmation button is placed at the end of the row (right side). This can be easily handled in Flutter using the `TextDirection` property on `Row`: <?code-excerpt "lib/widgets/ok_cancel_dialog.dart (RowTextDirection)"?> ```dart TextDirection btnDirection = DeviceType.isWindows ? TextDirection.rtl : TextDirection.ltr; return Row( children: [ const Spacer(), Row( textDirection: btnDirection, children: [ DialogButton( label: 'Cancel', onPressed: () => Navigator.pop(context, false), ), DialogButton( label: 'Ok', onPressed: () => Navigator.pop(context, true), ), ], ), ], ); ``` ![Sample of embedded image](/assets/images/docs/development/ui/layout/embed_image1.png){:width="75%"} ![Sample of embedded image](/assets/images/docs/development/ui/layout/embed_image2.png){:width="90%"} #### Menu bar Another common pattern on desktop apps is the menu bar. On Windows and Linux, this menu lives as part of the Chrome title bar, whereas on macOS, it's located along the top of the primary screen. Currently, you can specify custom menu bar entries using a prototype plugin, but it's expected that this functionality will eventually be integrated into the main SDK. It's worth mentioning that on Windows and Linux, you can't combine a custom title bar with a menu bar. When you create a custom title bar, you're replacing the native one completely, which means you also lose the integrated native menu bar. If you need both a custom title bar and a menu bar, you can achieve that by implementing it in Flutter, similar to a custom context menu. #### Drag and drop One of the core interactions for both touch-based and pointer-based inputs is drag and drop. Although this interaction is expected for both types of input, there are important differences to think about when it comes to scrolling lists of draggable items. Generally speaking, touch users expect to see drag handles to differentiate draggable areas from scrollable ones, or alternatively, to initiate a drag by using a long press gesture. This is because scrolling and dragging are both sharing a single finger for input. Mouse users have more input options. They can use a wheel or scrollbar to scroll, which generally eliminates the need for dedicated drag handles. If you look at the macOS Finder or Windows Explorer, you'll see that they work this way: you just select an item and start dragging. In Flutter, you can implement drag and drop in many ways. Discussing specific implementations is outside the scope of this article, but some high level options are: * Use the [`Draggable`][] and [`DragTarget`][] APIs directly for a custom look and feel. * Hook into `onPan` gesture events, and move an object yourself within a parent `Stack`. * Use one of the [pre-made list packages][] on pub.dev. [`Draggable`]: {{site.api}}/flutter/widgets/Draggable-class.html [`DragTarget`]: {{site.api}}/flutter/widgets/DragTarget-class.html [pre-made list packages]: {{site.pub}}/packages?q=reorderable+list ### Educate yourself on basic usability principles Of course, this page doesn't constitute an exhaustive list of the things you might consider. The more operating systems, form factors, and input devices you support, the more difficult it becomes to spec out every permutation in design. Taking time to learn basic usability principles as a developer empowers you to make better decisions, reduces back-and-forth iterations with design during production, and results in improved productivity with better outcomes. Here are some resources to get you started: * [Material guidelines on applying layout][] * [Material design for large screens][] * [Material guidelines on canonical layouts][] * [Build high quality apps (Android)][] * [UI design do's and don'ts (Apple)][] * [Human interface guidelines (Apple)][] * [Responsive design techniques (Microsoft)][] * [Machine sizes and breakpoints (Microsoft)][] [Build high quality apps (Android)]: {{site.android-dev}}/quality [Material guidelines on applying layout]: {{site.material}}/foundations/layout/applying-layout/window-size-classes [Material guidelines on canonical layouts]: {{site.material}}/foundations/layout/canonical-layouts/overview [Human interface guidelines (Apple)]: {{site.apple-dev}}/design/human-interface-guidelines/ [Material design for large screens]: {{site.material2}}/blog/material-design-for-large-screens [Machine sizes and breakpoints (Microsoft)]: https://docs.microsoft.com/en-us/windows/uwp/design/layout/screen-sizes-and-breakpoints-for-responsive-desig [Responsive design techniques (Microsoft)]: https://docs.microsoft.com/en-us/windows/uwp/design/layout/responsive-design [UI design do's and don'ts (Apple)]: {{site.apple-dev}}/design/tips/
website/src/ui/layout/responsive/building-adaptive-apps.md/0
{ "file_path": "website/src/ui/layout/responsive/building-adaptive-apps.md", "repo_id": "website", "token_count": 12408 }
1,331
--- title: Interaction model widgets short-title: Interaction description: > A catalog of Flutter's widgets supporting user interaction and navigation. --- {% include docs/catalogpage.html category="Interaction Models" %}
website/src/ui/widgets/interaction.md/0
{ "file_path": "website/src/ui/widgets/interaction.md", "repo_id": "website", "token_count": 58 }
1,332
// Copyright 2024 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:path/path.dart' as path; import '../utils.dart'; final class FormatDartCommand extends Command<int> { static const String _checkFlag = 'check'; FormatDartCommand() { argParser.addFlag( _checkFlag, defaultsTo: false, help: 'Just check the formatting, do not update.', ); } @override String get description => 'Format or check formatting of the site ' 'examples and tools.'; @override String get name => 'format-dart'; @override Future<int> run() async => formatDart( justCheck: argResults.get<bool>(_checkFlag, false), ); } int formatDart({bool justCheck = false}) { // Currently format all Dart files in the /tool directory // and everything in /examples. final directoriesToFormat = [ 'tool', ...Directory('examples') .listSync() .whereType<Directory>() .map((e) => e.path) .where((e) => path.basename(e) != 'codelabs' && !path.basename(e).startsWith('.')), ]; final dartFormatOutput = Process.runSync(Platform.resolvedExecutable, [ 'format', if (justCheck) ...['-o', 'none'], // Don't make changes if just checking. ...directoriesToFormat, ]); final normalOutput = dartFormatOutput.stdout.toString(); final errorOutput = dartFormatOutput.stderr.toString(); stdout.write(normalOutput); if (dartFormatOutput.exitCode != 0) { stderr.writeln('Error: Failed to run dart format:'); stderr.write(errorOutput); return 1; } // If just checking formatting, exit with error code if any files changed. if (justCheck && !normalOutput.contains('0 changed')) { stderr.writeln('Error: Some files needed to be formatted!'); return 1; } return 0; }
website/tool/flutter_site/lib/src/commands/format_dart.dart/0
{ "file_path": "website/tool/flutter_site/lib/src/commands/format_dart.dart", "repo_id": "website", "token_count": 703 }
1,333
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show Platform; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const ResizeablePage(), ); } } class ResizeablePage extends StatelessWidget { const ResizeablePage({super.key}); @override Widget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); final themePlatform = Theme.of(context).platform; return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Window properties', style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox(height: 8), SizedBox( width: 350, child: Table( textBaseline: TextBaseline.alphabetic, children: <TableRow>[ _fillTableRow( context: context, property: 'Window Size', value: '${mediaQuery.size.width.toStringAsFixed(1)} x ' '${mediaQuery.size.height.toStringAsFixed(1)}', ), _fillTableRow( context: context, property: 'Device Pixel Ratio', value: mediaQuery.devicePixelRatio.toStringAsFixed(2), ), _fillTableRow( context: context, property: 'Platform.isXXX', value: platformDescription(), ), _fillTableRow( context: context, property: 'Theme.of(ctx).platform', value: themePlatform.toString(), ), ], ), ), ], ), ), ); } TableRow _fillTableRow( {required BuildContext context, required String property, required String value}) { return TableRow( children: [ TableCell( verticalAlignment: TableCellVerticalAlignment.baseline, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(property), ), ), TableCell( verticalAlignment: TableCellVerticalAlignment.baseline, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(value), ), ), ], ); } String platformDescription() { if (kIsWeb) { return 'Web'; } else if (Platform.isAndroid) { return 'Android'; } else if (Platform.isIOS) { return 'iOS'; } else if (Platform.isWindows) { return 'Windows'; } else if (Platform.isMacOS) { return 'macOS'; } else if (Platform.isLinux) { return 'Linux'; } else if (Platform.isFuchsia) { return 'Fuchsia'; } else { return 'Unknown'; } } }
codelabs/adaptive_app/step_03/lib/main.dart/0
{ "file_path": "codelabs/adaptive_app/step_03/lib/main.dart", "repo_id": "codelabs", "token_count": 1699 }
0
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:googleapis/youtube/v3.dart'; import 'package:http/http.dart' as http; class FlutterDevPlaylists extends ChangeNotifier { FlutterDevPlaylists({ required String flutterDevAccountId, required String youTubeApiKey, }) : _flutterDevAccountId = flutterDevAccountId { _api = YouTubeApi( _ApiKeyClient( client: http.Client(), key: youTubeApiKey, ), ); _loadPlaylists(); } Future<void> _loadPlaylists() async { String? nextPageToken; _playlists.clear(); do { final response = await _api.playlists.list( ['snippet', 'contentDetails', 'id'], channelId: _flutterDevAccountId, maxResults: 50, pageToken: nextPageToken, ); _playlists.addAll(response.items!); _playlists.sort((a, b) => a.snippet!.title! .toLowerCase() .compareTo(b.snippet!.title!.toLowerCase())); notifyListeners(); nextPageToken = response.nextPageToken; } while (nextPageToken != null); } final String _flutterDevAccountId; late final YouTubeApi _api; final List<Playlist> _playlists = []; List<Playlist> get playlists => UnmodifiableListView(_playlists); final Map<String, List<PlaylistItem>> _playlistItems = {}; List<PlaylistItem> playlistItems({required String playlistId}) { if (!_playlistItems.containsKey(playlistId)) { _playlistItems[playlistId] = []; _retrievePlaylist(playlistId); } return UnmodifiableListView(_playlistItems[playlistId]!); } Future<void> _retrievePlaylist(String playlistId) async { String? nextPageToken; do { var response = await _api.playlistItems.list( ['snippet', 'contentDetails'], playlistId: playlistId, maxResults: 25, pageToken: nextPageToken, ); var items = response.items; if (items != null) { _playlistItems[playlistId]!.addAll(items); } notifyListeners(); nextPageToken = response.nextPageToken; } while (nextPageToken != null); } } class _ApiKeyClient extends http.BaseClient { _ApiKeyClient({required this.key, required this.client}); final String key; final http.Client client; @override Future<http.StreamedResponse> send(http.BaseRequest request) { final url = request.url.replace(queryParameters: <String, List<String>>{ ...request.url.queryParametersAll, 'key': [key] }); return client.send(http.Request(request.method, url)); } }
codelabs/adaptive_app/step_04/lib/src/app_state.dart/0
{ "file_path": "codelabs/adaptive_app/step_04/lib/src/app_state.dart", "repo_id": "codelabs", "token_count": 1037 }
1
#import "GeneratedPluginRegistrant.h"
codelabs/adaptive_app/step_05/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/adaptive_app/step_05/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
2
#import "GeneratedPluginRegistrant.h"
codelabs/adaptive_app/step_07/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/adaptive_app/step_07/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
3
name: yt_cors_proxy description: A YouTube CORS Proxy Server. version: 1.0.0 environment: sdk: ^3.3.0-279.2.beta dependencies: http: ^1.2.0 shelf: ^1.4.0 shelf_cors_headers: ^0.1.5 dev_dependencies: lints: ^3.0.0
codelabs/adaptive_app/step_07/yt_cors_proxy/pubspec.yaml/0
{ "file_path": "codelabs/adaptive_app/step_07/yt_cors_proxy/pubspec.yaml", "repo_id": "codelabs", "token_count": 107 }
4
import 'package:flutter/material.dart'; void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: Text('Hello World!'), ), ), ); } }
codelabs/animated-responsive-layout/step_03/lib/main.dart/0
{ "file_path": "codelabs/animated-responsive-layout/step_03/lib/main.dart", "repo_id": "codelabs", "token_count": 143 }
5
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/animated-responsive-layout/step_05/android/gradle.properties/0
{ "file_path": "codelabs/animated-responsive-layout/step_05/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
6
#import "GeneratedPluginRegistrant.h"
codelabs/animated-responsive-layout/step_05/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/animated-responsive-layout/step_05/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
7
// Copyright 2022 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 'models/data.dart' as data; import 'models/models.dart'; import 'widgets/disappearing_bottom_navigation_bar.dart'; import 'widgets/disappearing_navigation_rail.dart'; import 'widgets/email_list_view.dart'; void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(useMaterial3: true), home: Feed(currentUser: data.user_0), ); } } class Feed extends StatefulWidget { const Feed({ super.key, required this.currentUser, }); final User currentUser; @override State<Feed> createState() => _FeedState(); } class _FeedState extends State<Feed> { late final _colorScheme = Theme.of(context).colorScheme; late final _backgroundColor = Color.alphaBlend( _colorScheme.primary.withOpacity(0.14), _colorScheme.surface); int selectedIndex = 0; bool wideScreen = false; @override void didChangeDependencies() { super.didChangeDependencies(); final double width = MediaQuery.of(context).size.width; wideScreen = width > 600; } @override Widget build(BuildContext context) { return Scaffold( body: Row( children: [ if (wideScreen) DisappearingNavigationRail( selectedIndex: selectedIndex, backgroundColor: _backgroundColor, onDestinationSelected: (index) { setState(() { selectedIndex = index; }); }, ), Expanded( child: Container( color: _backgroundColor, child: EmailListView( selectedIndex: selectedIndex, onSelected: (index) { setState(() { selectedIndex = index; }); }, currentUser: widget.currentUser, ), ), ), ], ), floatingActionButton: wideScreen ? null : FloatingActionButton( backgroundColor: _colorScheme.tertiaryContainer, foregroundColor: _colorScheme.onTertiaryContainer, onPressed: () {}, child: const Icon(Icons.add), ), bottomNavigationBar: wideScreen ? null : DisappearingBottomNavigationBar( selectedIndex: selectedIndex, onDestinationSelected: (index) { setState(() { selectedIndex = index; }); }, ), ); } }
codelabs/animated-responsive-layout/step_06/lib/main.dart/0
{ "file_path": "codelabs/animated-responsive-layout/step_06/lib/main.dart", "repo_id": "codelabs", "token_count": 1302 }
8
package com.example.animated_responsive_layout import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
codelabs/animated-responsive-layout/step_07/android/app/src/main/kotlin/com/example/animated_responsive_layout/MainActivity.kt/0
{ "file_path": "codelabs/animated-responsive-layout/step_07/android/app/src/main/kotlin/com/example/animated_responsive_layout/MainActivity.kt", "repo_id": "codelabs", "token_count": 38 }
9
// Copyright 2022 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 'animations.dart'; import 'models/data.dart' as data; import 'models/models.dart'; import 'widgets/animated_floating_action_button.dart'; import 'widgets/disappearing_bottom_navigation_bar.dart'; import 'widgets/disappearing_navigation_rail.dart'; import 'widgets/email_list_view.dart'; void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(useMaterial3: true), home: Feed(currentUser: data.user_0), ); } } class Feed extends StatefulWidget { const Feed({ super.key, required this.currentUser, }); final User currentUser; @override State<Feed> createState() => _FeedState(); } class _FeedState extends State<Feed> with SingleTickerProviderStateMixin { late final _colorScheme = Theme.of(context).colorScheme; late final _backgroundColor = Color.alphaBlend( _colorScheme.primary.withOpacity(0.14), _colorScheme.surface); late final _controller = AnimationController( duration: const Duration(milliseconds: 1000), reverseDuration: const Duration(milliseconds: 1250), value: 0, vsync: this); late final _railAnimation = RailAnimation(parent: _controller); late final _railFabAnimation = RailFabAnimation(parent: _controller); late final _barAnimation = BarAnimation(parent: _controller); int selectedIndex = 0; bool controllerInitialized = false; @override void didChangeDependencies() { super.didChangeDependencies(); final double width = MediaQuery.of(context).size.width; final AnimationStatus status = _controller.status; if (width > 600) { if (status != AnimationStatus.forward && status != AnimationStatus.completed) { _controller.forward(); } } else { if (status != AnimationStatus.reverse && status != AnimationStatus.dismissed) { _controller.reverse(); } } if (!controllerInitialized) { controllerInitialized = true; _controller.value = width > 600 ? 1 : 0; } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (context, _) { return Scaffold( body: Row( children: [ DisappearingNavigationRail( railAnimation: _railAnimation, railFabAnimation: _railFabAnimation, selectedIndex: selectedIndex, backgroundColor: _backgroundColor, onDestinationSelected: (index) { setState(() { selectedIndex = index; }); }, ), Expanded( child: Container( color: _backgroundColor, child: EmailListView( selectedIndex: selectedIndex, onSelected: (index) { setState(() { selectedIndex = index; }); }, currentUser: widget.currentUser, ), ), ), ], ), floatingActionButton: AnimatedFloatingActionButton( animation: _barAnimation, onPressed: () {}, child: const Icon(Icons.add), ), bottomNavigationBar: DisappearingBottomNavigationBar( barAnimation: _barAnimation, selectedIndex: selectedIndex, onDestinationSelected: (index) { setState(() { selectedIndex = index; }); }, ), ); }, ); } }
codelabs/animated-responsive-layout/step_07/lib/main.dart/0
{ "file_path": "codelabs/animated-responsive-layout/step_07/lib/main.dart", "repo_id": "codelabs", "token_count": 1767 }
10
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class StarButton extends StatefulWidget { const StarButton({super.key}); @override State<StarButton> createState() => _StarButtonState(); } class _StarButtonState extends State<StarButton> { bool state = false; late final ColorScheme _colorScheme = Theme.of(context).colorScheme; Icon get icon { final IconData iconData = state ? Icons.star : Icons.star_outline; return Icon( iconData, color: Colors.grey, size: 20, ); } void _toggle() { setState(() { state = !state; }); } double get turns => state ? 1 : 0; @override Widget build(BuildContext context) { return AnimatedRotation( turns: turns, curve: Curves.decelerate, duration: const Duration(milliseconds: 300), child: FloatingActionButton( elevation: 0, shape: const CircleBorder(), backgroundColor: _colorScheme.surface, onPressed: () => _toggle(), child: Padding( padding: const EdgeInsets.all(10.0), child: icon, ), ), ); } }
codelabs/animated-responsive-layout/step_08/lib/widgets/star_button.dart/0
{ "file_path": "codelabs/animated-responsive-layout/step_08/lib/widgets/star_button.dart", "repo_id": "codelabs", "token_count": 481 }
11
// Copyright 2022 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 '../../../shared/classes/classes.dart'; import '../../../shared/extensions.dart'; import '../../../shared/views/outlined_card.dart'; import '../../../shared/views/views.dart'; class ArtistCard extends StatelessWidget { const ArtistCard({ super.key, required this.artist, }); final Artist artist; @override Widget build(BuildContext context) { Song nowPlaying = artist.songs[Random().nextInt(artist.songs.length)]; return OutlinedCard( child: LayoutBuilder( builder: (context, dimens) => Row( children: [ SizedBox( width: dimens.maxWidth * 0.4, child: Image.asset( artist.image.image, fit: BoxFit.cover, ), ), Expanded( child: Padding( padding: const EdgeInsets.only(left: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.fromLTRB(0, 0, 15, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( artist.name, style: context.titleMedium, overflow: TextOverflow.ellipsis, maxLines: 1, ), const SizedBox(height: 10), Text( artist.bio, overflow: TextOverflow.ellipsis, style: context.labelSmall, maxLines: 3, ), ]), ), if (dimens.maxHeight > 100) Row( children: [ HoverableSongPlayButton( size: const Size(50, 50), song: nowPlaying, child: Icon(Icons.play_circle, color: context.colors.tertiary), ), Text( nowPlaying.title, maxLines: 1, overflow: TextOverflow.clip, style: context.labelMedium, ), ], ), ], ), ), ), ], ), ), ); } }
codelabs/boring_to_beautiful/final/lib/src/features/artists/view/artist_card.dart/0
{ "file_path": "codelabs/boring_to_beautiful/final/lib/src/features/artists/view/artist_card.dart", "repo_id": "codelabs", "token_count": 1859 }
12
// Copyright 2022 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 'package:go_router/go_router.dart'; import '../../../shared/classes/classes.dart'; import '../../../shared/extensions.dart'; import '../../../shared/views/adaptive_image_card.dart'; import '../../../shared/views/views.dart'; import 'playlist_songs.dart'; class PlaylistScreen extends StatelessWidget { const PlaylistScreen({required this.playlist, super.key}); final Playlist playlist; @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { final colors = Theme.of(context).colorScheme; final double headerHeight = constraints.isMobile ? max(constraints.biggest.height * 0.5, 450) : max(constraints.biggest.height * 0.25, 250); if (constraints.isMobile) { return Scaffold( appBar: AppBar( leading: BackButton( onPressed: () => GoRouter.of(context).go('/playlists'), ), title: Text(playlist.title), actions: [ IconButton( icon: const Icon(Icons.play_circle_fill), onPressed: () {}, ), IconButton( onPressed: () {}, icon: const Icon(Icons.shuffle), ), ], ), body: ArticleContent( child: PlaylistSongs( playlist: playlist, constraints: constraints, ), ), ); } return Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( leading: BackButton( onPressed: () => GoRouter.of(context).go('/playlists'), ), expandedHeight: headerHeight, pinned: false, flexibleSpace: FlexibleSpaceBar( background: AdaptiveImageCard( axis: constraints.isMobile ? Axis.vertical : Axis.horizontal, constraints: constraints.copyWith(maxHeight: headerHeight).normalize(), image: playlist.cover.image, child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( 'PLAYLIST', style: context.titleSmall! .copyWith(color: colors.onSurface), ), Text( playlist.title, style: context.displaySmall! .copyWith(color: colors.onSurface), ), Text( playlist.description, style: context.bodyLarge!.copyWith( color: colors.onSurface.withOpacity(0.8), ), ), const SizedBox(height: 8), Row( children: [ IconButton( icon: Icon( Icons.play_circle_fill, color: colors.tertiary, ), onPressed: () {}, ), TextButton.icon( onPressed: () {}, icon: Icon( Icons.shuffle, color: colors.tertiary, ), label: Text( 'Shuffle', style: context.bodySmall!.copyWith( color: colors.tertiary, ), ), ), ], ), ], ), ), ), ), SliverToBoxAdapter( child: ArticleContent( child: PlaylistSongs( playlist: playlist, constraints: constraints, ), ), ), ], ), ); }); } }
codelabs/boring_to_beautiful/final/lib/src/features/playlists/view/playlist_screen.dart/0
{ "file_path": "codelabs/boring_to_beautiful/final/lib/src/features/playlists/view/playlist_screen.dart", "repo_id": "codelabs", "token_count": 2765 }
13
// Copyright 2022 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. part of 'playback_bloc.dart'; @Freezed() class PlaybackEvent with _$PlaybackEvent { const factory PlaybackEvent.togglePlayPause() = TogglePlayPause; const factory PlaybackEvent.changeSong(Song song) = ChangeSong; const factory PlaybackEvent.setVolume(double value) = SetVolume; const factory PlaybackEvent.toggleMute() = ToggleMute; /// Used to move to a specific timestamp in a song, likely because the user /// has dragged the playback bar. Values should be between 0 and 1. const factory PlaybackEvent.moveToInSong(double percent) = MoveToInSong; /// Used to indicate incremental progress in the song that is currently /// playing. const factory PlaybackEvent.songProgress(Duration duration) = SongProgress; }
codelabs/boring_to_beautiful/final/lib/src/shared/playback/bloc/playback_event.dart/0
{ "file_path": "codelabs/boring_to_beautiful/final/lib/src/shared/playback/bloc/playback_event.dart", "repo_id": "codelabs", "token_count": 239 }
14
// Copyright 2022 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:url_launcher/url_launcher.dart'; import '../classes/classes.dart'; import '../providers/providers.dart'; import 'views.dart'; class Events extends StatelessWidget { const Events({super.key, required this.artist, required this.constraints}); final Artist artist; final BoxConstraints constraints; @override Widget build(BuildContext context) { final theme = ThemeProvider.of(context); if (constraints.maxWidth > 820) { return ConstrainedBox( constraints: BoxConstraints(minWidth: constraints.minWidth), child: DataTable( horizontalMargin: 5.0, columns: const <DataColumn>[ DataColumn( label: Text( 'Date', ), numeric: true, ), DataColumn( label: Text( 'Event', ), ), DataColumn( label: Text( 'Location', ), ), DataColumn( label: Text( 'More info', ), ), ], rows: <DataRow>[ for (final event in artist.events) DataRow( cells: <DataCell>[ DataCell( Text(event.date), ), DataCell( Row(children: [ Expanded(child: Text(event.title)), ]), ), DataCell( Text(event.location), ), DataCell( Clickable( child: Text( event.link, style: TextStyle( color: linkColor.value(theme), decoration: TextDecoration.underline, ), ), onTap: () => launchUrl(Uri.parse('https://docs.flutter.dev')), ), ), ], ), ], ), ); } return ListView( shrinkWrap: true, children: artist.events.map((e) => buildTile(context, e)).toList(), ); } Widget buildTile(BuildContext context, Event event) { final dateParts = event.date.split('/'); final colors = Theme.of(context).colorScheme; return ListTile( leading: Container( decoration: BoxDecoration( color: colors.primaryContainer, borderRadius: BorderRadius.circular(100), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Text.rich( TextSpan( children: [ TextSpan( text: dateParts[0], style: TextStyle( fontSize: 18.0, color: colors.onPrimaryContainer, ), ), TextSpan( text: '/', style: TextStyle( fontSize: 18.0, color: colors.onPrimaryContainer, ), ), TextSpan( text: dateParts[1], style: TextStyle( fontSize: 14.0, color: colors.onPrimaryContainer, ), ), ], ), ), ), ), title: Text(event.title), subtitle: Text(event.location), trailing: IconButton( icon: const Icon(Icons.info_outline), onPressed: () {}, ), ); } }
codelabs/boring_to_beautiful/final/lib/src/shared/views/events.dart/0
{ "file_path": "codelabs/boring_to_beautiful/final/lib/src/shared/views/events.dart", "repo_id": "codelabs", "token_count": 2268 }
15
// Copyright 2022 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 './classes.dart'; class News { const News({ required this.title, required this.author, required this.blurb, required this.image, }); final String title; final String author; final String blurb; final MyArtistImage image; }
codelabs/boring_to_beautiful/step_01/lib/src/shared/classes/news.dart/0
{ "file_path": "codelabs/boring_to_beautiful/step_01/lib/src/shared/classes/news.dart", "repo_id": "codelabs", "token_count": 130 }
16
// Copyright 2022 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 'image_clipper.dart'; class AdaptiveImageCard extends StatelessWidget { const AdaptiveImageCard({ super.key, required this.image, required this.child, required this.constraints, this.axis = Axis.horizontal, }); final String image; final Widget child; final BoxConstraints constraints; final Axis axis; @override Widget build(BuildContext context) { if (axis == Axis.vertical) { return Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: [ Padding( padding: const EdgeInsets.all(20), child: ClippedImage( image, height: constraints.biggest.height * 0.4, ), ), Expanded( child: Padding( padding: const EdgeInsets.all(20), child: child, ), ), ], ); } return Padding( padding: const EdgeInsets.only( left: 20, bottom: 20, top: 20, ), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [ const SizedBox(width: 40), Container( constraints: const BoxConstraints(maxWidth: 200), child: ClippedImage( image, width: constraints.biggest.height * 0.8, height: constraints.biggest.height * 0.8, fit: BoxFit.fitWidth, ), ), Expanded( child: Padding( padding: const EdgeInsets.all(20), child: child, ), ) ], ), ); } }
codelabs/boring_to_beautiful/step_01/lib/src/shared/views/adaptive_image_card.dart/0
{ "file_path": "codelabs/boring_to_beautiful/step_01/lib/src/shared/views/adaptive_image_card.dart", "repo_id": "codelabs", "token_count": 965 }
17
// Copyright 2022 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_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart' as go; import 'package:universal_platform/universal_platform.dart'; import '../playback/bloc/bloc.dart'; import '../router.dart' as router; import 'adaptive_navigation.dart'; import 'views.dart'; class RootLayout extends StatelessWidget { const RootLayout({ super.key, required this.child, required this.currentIndex, }); final Widget child; final int currentIndex; static const _switcherKey = ValueKey('switcherKey'); static const _navigationRailKey = ValueKey('navigationRailKey'); @override Widget build(BuildContext context) { final bloc = BlocProvider.of<PlaybackBloc>(context); return BlocBuilder<PlaybackBloc, PlaybackState>( bloc: bloc, builder: (context, state) => LayoutBuilder(builder: (context, dimens) { void onSelected(int index) { final destination = router.destinations[index]; go.GoRouter.of(context).go(destination.route); } final current = state.songWithProgress; return AdaptiveNavigation( key: _navigationRailKey, destinations: router.destinations .map((e) => NavigationDestination( icon: e.icon, label: e.label, )) .toList(), selectedIndex: currentIndex, onDestinationSelected: onSelected, child: Column( children: [ Expanded( child: _Switcher( key: _switcherKey, child: child, ), ), if (current != null) const BottomBar(), ], ), ); }), ); } } class _Switcher extends StatelessWidget { final Widget child; const _Switcher({ required this.child, super.key, }); @override Widget build(BuildContext context) { return UniversalPlatform.isDesktop ? child : AnimatedSwitcher( key: key, duration: const Duration(milliseconds: 200), switchInCurve: Curves.easeInOut, switchOutCurve: Curves.easeInOut, child: child, ); } }
codelabs/boring_to_beautiful/step_01/lib/src/shared/views/root_layout.dart/0
{ "file_path": "codelabs/boring_to_beautiful/step_01/lib/src/shared/views/root_layout.dart", "repo_id": "codelabs", "token_count": 1070 }
18
#import "GeneratedPluginRegistrant.h"
codelabs/brick_breaker/step_04/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/brick_breaker/step_04/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
19