From 0909e96c366f2f06643dd8f3be779a84aec37750 Mon Sep 17 00:00:00 2001 From: Michael Goderbauer Date: Thu, 8 Jun 2017 15:55:31 -0700 Subject: [PATCH] Format all Dart code that doesn't contain assert initilizers (#109) Formatting assert initilizers is blocked on https://github.com/dart-lang/dart_style/issues/522 --- packages/android_intent/example/lib/main.dart | 18 +- .../firebase_analytics/example/lib/main.dart | 4 +- .../lib/firebase_analytics.dart | 56 +++-- .../test/firebase_analytics_test.dart | 236 +++++++++++------- packages/firebase_auth/example/lib/main.dart | 43 ++-- packages/firebase_auth/lib/firebase_auth.dart | 10 +- .../test/firebase_auth_test.dart | 5 +- .../firebase_database/example/lib/main.dart | 29 ++- .../lib/src/database_reference.dart | 29 ++- .../lib/src/firebase_database.dart | 7 +- .../lib/src/utils/push_id_generator.dart | 1 - .../lib/ui/firebase_animated_list.dart | 15 +- .../lib/ui/firebase_list.dart | 7 +- .../lib/ui/firebase_sorted_list.dart | 9 +- .../lib/ui/utils/stream_subscriber_mixin.dart | 5 +- .../test/firebase_database_test.dart | 138 ++++++---- .../lib/firebase_messaging.dart | 4 +- .../firebase_storage/example/lib/main.dart | 16 +- .../lib/firebase_storage.dart | 24 +- packages/google_sign_in/example/lib/main.dart | 80 +++--- .../google_sign_in/lib/google_sign_in.dart | 14 +- .../test/google_sign_in_test.dart | 47 ++-- packages/image_picker/example/lib/main.dart | 20 +- packages/image_picker/lib/image_picker.dart | 3 +- packages/path_provider/example/lib/main.dart | 24 +- packages/path_provider/lib/path_provider.dart | 92 ++++--- .../test/path_provider_test.dart | 9 +- packages/share/example/lib/main.dart | 53 ++-- .../shared_preferences/example/lib/main.dart | 28 +-- .../lib/shared_preferences.dart | 4 +- .../test/shared_preferences_test.dart | 71 +++--- packages/url_launcher/lib/url_launcher.dart | 6 +- .../url_launcher/test/url_launcher_test.dart | 12 +- 33 files changed, 629 insertions(+), 490 deletions(-) diff --git a/packages/android_intent/example/lib/main.dart b/packages/android_intent/example/lib/main.dart index 83efd95a27d1..48a67b6cfa8c 100644 --- a/packages/android_intent/example/lib/main.dart +++ b/packages/android_intent/example/lib/main.dart @@ -25,22 +25,24 @@ class MyApp extends StatelessWidget { } class MyHomePage extends StatelessWidget { - @override Widget build(BuildContext context) { Widget body; if (const LocalPlatform().isAndroid) { body = new GestureDetector( - child: const Center(child: - const Text('Click here to launch play store with New York Times app.')), - onTap: () { + child: const Center( + child: const Text( + 'Click here to launch play store with New York Times app.')), + onTap: () { final AndroidIntent intent = const AndroidIntent( - action: 'action_view', - data: 'https://play.google.com/store/apps/details?id=com.nytimes.android'); + action: 'action_view', + data: + 'https://play.google.com/store/apps/details?id=com.nytimes.android'); intent.launch(); - }); + }); } else { - body = const Center(child: const Text('This plugin only works with Android')); + body = const Center( + child: const Text('This plugin only works with Android')); } return new Scaffold( appBar: new AppBar( diff --git a/packages/firebase_analytics/example/lib/main.dart b/packages/firebase_analytics/example/lib/main.dart index ec15812ced98..84256fac0c28 100755 --- a/packages/firebase_analytics/example/lib/main.dart +++ b/packages/firebase_analytics/example/lib/main.dart @@ -283,7 +283,9 @@ class _MyHomePageState extends State { child: const Text('Test setUserProperty'), onPressed: _testSetUserProperty, ), - new Text(_message, style: const TextStyle(color: const Color.fromARGB(255, 0, 155, 0))), + new Text(_message, + style: + const TextStyle(color: const Color.fromARGB(255, 0, 155, 0))), ], ), ); diff --git a/packages/firebase_analytics/lib/firebase_analytics.dart b/packages/firebase_analytics/lib/firebase_analytics.dart index 62b2a0800abd..458345ed96f9 100755 --- a/packages/firebase_analytics/lib/firebase_analytics.dart +++ b/packages/firebase_analytics/lib/firebase_analytics.dart @@ -11,7 +11,8 @@ import 'package:flutter/foundation.dart'; /// Firebase Analytics API. class FirebaseAnalytics { - static final FirebaseAnalytics _instance = new FirebaseAnalytics.private(const MethodChannel('firebase_analytics')); + static final FirebaseAnalytics _instance = + new FirebaseAnalytics.private(const MethodChannel('firebase_analytics')); /// Provides an instance of this class. factory FirebaseAnalytics() => _instance; @@ -20,10 +21,10 @@ class FirebaseAnalytics { /// e.g. in tests, is OK. @visibleForTesting FirebaseAnalytics.private(MethodChannel platformChannel) - : _channel = platformChannel, - android = defaultTargetPlatform == TargetPlatform.android - ? new FirebaseAnalyticsAndroid.private(platformChannel) - : null; + : _channel = platformChannel, + android = defaultTargetPlatform == TargetPlatform.android + ? new FirebaseAnalyticsAndroid.private(platformChannel) + : null; final MethodChannel _channel; @@ -40,10 +41,11 @@ class FirebaseAnalytics { final FirebaseAnalyticsAndroid android; /// Logs a custom Flutter Analytics event with the given [name] and event [parameters]. - Future logEvent({@required String name, Map parameters}) async { + Future logEvent( + {@required String name, Map parameters}) async { if (_reservedEventNames.contains(name)) { - throw new ArgumentError.value(name, 'name', - 'Event name is reserved and cannot be used'); + throw new ArgumentError.value( + name, 'name', 'Event name is reserved and cannot be used'); } const String kReservedPrefix = 'firebase_'; @@ -65,8 +67,7 @@ class FirebaseAnalytics { /// /// [1]: https://www.google.com/policies/privacy/ Future setUserId(String id) async { - if (id == null) - throw new ArgumentError.notNull('id'); + if (id == null) throw new ArgumentError.notNull('id'); await _channel.invokeMethod('setUserId', id); } @@ -88,9 +89,9 @@ class FirebaseAnalytics { /// /// https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.html#setCurrentScreen(android.app.Activity, java.lang.String, java.lang.String) /// https://firebase.google.com/docs/reference/ios/firebaseanalytics/api/reference/Classes/FIRAnalytics#setscreennamescreenclass - Future setCurrentScreen({@required String screenName, String screenClassOverride}) async { - if (screenName == null) - throw new ArgumentError.notNull('screenName'); + Future setCurrentScreen( + {@required String screenName, String screenClassOverride}) async { + if (screenName == null) throw new ArgumentError.notNull('screenName'); await _channel.invokeMethod('setCurrentScreen', { 'screenName': screenName, @@ -110,15 +111,20 @@ class FirebaseAnalytics { /// alphanumeric characters or underscores and must start with an alphabetic /// character. The "firebase_" prefix is reserved and should not be used for /// user property names. - Future setUserProperty({@required String name, @required String value}) async { - if (name == null) - throw new ArgumentError.notNull('name'); + Future setUserProperty( + {@required String name, @required String value}) async { + if (name == null) throw new ArgumentError.notNull('name'); - if (name.isEmpty || name.length > 24 || name.indexOf(_alpha) != 0 || name.contains(_nonAlphaNumeric)) - throw new ArgumentError.value(name, 'name', 'must contain 1 to 24 alphanumeric characters.'); + if (name.isEmpty || + name.length > 24 || + name.indexOf(_alpha) != 0 || + name.contains(_nonAlphaNumeric)) + throw new ArgumentError.value( + name, 'name', 'must contain 1 to 24 alphanumeric characters.'); if (name.startsWith('firebase_')) - throw new ArgumentError.value(name, 'name', '"firebase_" prefix is reserved'); + throw new ArgumentError.value( + name, 'name', '"firebase_" prefix is reserved'); await _channel.invokeMethod('setUserProperty', { 'name': name, @@ -775,8 +781,7 @@ class FirebaseAnalyticsAndroid { /// /// This setting is persisted across app sessions. By default it is enabled. Future setAnalyticsCollectionEnabled(bool enabled) async { - if (enabled == null) - throw new ArgumentError.notNull('enabled'); + if (enabled == null) throw new ArgumentError.notNull('enabled'); await _channel.invokeMethod('setAnalyticsCollectionEnabled', enabled); } @@ -785,8 +790,7 @@ class FirebaseAnalyticsAndroid { /// /// The default value is 10000 (10 seconds). Future setMinimumSessionDuration(int milliseconds) async { - if (milliseconds == null) - throw new ArgumentError.notNull('milliseconds'); + if (milliseconds == null) throw new ArgumentError.notNull('milliseconds'); await _channel.invokeMethod('setMinimumSessionDuration', milliseconds); } @@ -795,8 +799,7 @@ class FirebaseAnalyticsAndroid { /// /// The default value is 1800000 (30 minutes). Future setSessionTimeoutDuration(int milliseconds) async { - if (milliseconds == null) - throw new ArgumentError.notNull('milliseconds'); + if (milliseconds == null) throw new ArgumentError.notNull('milliseconds'); await _channel.invokeMethod('setSessionTimeoutDuration', milliseconds); } @@ -808,8 +811,7 @@ class FirebaseAnalyticsAndroid { Map filterOutNulls(Map parameters) { final Map filtered = {}; parameters.forEach((String key, dynamic value) { - if (value != null) - filtered[key] = value; + if (value != null) filtered[key] = value; }); return filtered; } diff --git a/packages/firebase_analytics/test/firebase_analytics_test.dart b/packages/firebase_analytics/test/firebase_analytics_test.dart index 6831344aa0bf..c39e27cb36c7 100755 --- a/packages/firebase_analytics/test/firebase_analytics_test.dart +++ b/packages/firebase_analytics/test/firebase_analytics_test.dart @@ -14,7 +14,11 @@ import 'package:firebase_analytics/firebase_analytics.dart'; void main() { group('filterOutNulls', () { test('filters out null values', () { - final Map original = {'a': 1, 'b': null, 'c': 'd'}; + final Map original = { + 'a': 1, + 'b': null, + 'c': 'd' + }; final Map filtered = filterOutNulls(original); expect(filtered, isNot(same(original))); @@ -35,7 +39,8 @@ void main() { invokedMethod = null; arguments = null; - when(mockChannel.invokeMethod(any, any)).thenAnswer((Invocation invocation) { + when(mockChannel.invokeMethod(any, any)) + .thenAnswer((Invocation invocation) { invokedMethod = invocation.positionalArguments[0]; arguments = invocation.positionalArguments[1]; }); @@ -50,7 +55,9 @@ void main() { }); test('setCurrentScreen', () async { - await analytics.setCurrentScreen(screenName: 'test-screen-name', screenClassOverride: 'test-class-override'); + await analytics.setCurrentScreen( + screenName: 'test-screen-name', + screenClassOverride: 'test-class-override'); expect(invokedMethod, 'setCurrentScreen'); expect(arguments, { 'screenName': 'test-screen-name', @@ -69,15 +76,21 @@ void main() { test('setUserProperty rejects invalid names', () async { // invalid character - expect(analytics.setUserProperty(name: 'test-name', value: 'test-value'), throwsArgumentError); + expect(analytics.setUserProperty(name: 'test-name', value: 'test-value'), + throwsArgumentError); // non-alpha first character - expect(analytics.setUserProperty(name: '0test', value: 'test-value'), throwsArgumentError); + expect(analytics.setUserProperty(name: '0test', value: 'test-value'), + throwsArgumentError); // null - expect(analytics.setUserProperty(name: null, value: 'test-value'), throwsArgumentError); + expect(analytics.setUserProperty(name: null, value: 'test-value'), + throwsArgumentError); // blank - expect(analytics.setUserProperty(name: '', value: 'test-value'), throwsArgumentError); + expect(analytics.setUserProperty(name: '', value: 'test-value'), + throwsArgumentError); // reserved prefix - expect(analytics.setUserProperty(name: 'firebase_test', value: 'test-value'), throwsArgumentError); + expect( + analytics.setUserProperty(name: 'firebase_test', value: 'test-value'), + throwsArgumentError); }); test('setAnalyticsCollectionEnabled', () async { @@ -111,7 +124,8 @@ void main() { name = null; parameters = null; - when(mockChannel.invokeMethod('logEvent', any)).thenAnswer((Invocation invocation) { + when(mockChannel.invokeMethod('logEvent', any)) + .thenAnswer((Invocation invocation) { final Map args = invocation.positionalArguments[1]; name = args['name']; parameters = args['parameters']; @@ -125,7 +139,8 @@ void main() { }); test('logEvent log events', () async { - await analytics.logEvent(name: 'test-event', parameters: {'a': 'b'}); + await analytics.logEvent( + name: 'test-event', parameters: {'a': 'b'}); expect(name, 'test-event'); expect(parameters, {'a': 'b'}); }); @@ -147,114 +162,149 @@ void main() { smokeTest('add_payment_info', () => analytics.logAddPaymentInfo()); - smokeTest('add_to_cart', () => analytics.logAddToCart( - itemId: 'test-id', - itemName: 'test-name', - itemCategory: 'test-category', - quantity: 5, - )); - - smokeTest('add_to_wishlist', () => analytics.logAddToWishlist( - itemId: 'test-id', - itemName: 'test-name', - itemCategory: 'test-category', - quantity: 5, - )); + smokeTest( + 'add_to_cart', + () => analytics.logAddToCart( + itemId: 'test-id', + itemName: 'test-name', + itemCategory: 'test-category', + quantity: 5, + )); + + smokeTest( + 'add_to_wishlist', + () => analytics.logAddToWishlist( + itemId: 'test-id', + itemName: 'test-name', + itemCategory: 'test-category', + quantity: 5, + )); smokeTest('app_open', () => analytics.logAppOpen()); smokeTest('begin_checkout', () => analytics.logBeginCheckout()); - smokeTest('campaign_details', () => analytics.logCampaignDetails( - source: 'test-source', - medium: 'test-medium', - campaign: 'test-campaign', - )); - - smokeTest('earn_virtual_currency', () => analytics.logEarnVirtualCurrency( - virtualCurrencyName: 'bitcoin', - value: 34, - )); + smokeTest( + 'campaign_details', + () => analytics.logCampaignDetails( + source: 'test-source', + medium: 'test-medium', + campaign: 'test-campaign', + )); + + smokeTest( + 'earn_virtual_currency', + () => analytics.logEarnVirtualCurrency( + virtualCurrencyName: 'bitcoin', + value: 34, + )); smokeTest('ecommerce_purchase', () => analytics.logEcommercePurchase()); smokeTest('generate_lead', () => analytics.logGenerateLead()); - smokeTest('join_group', () => analytics.logJoinGroup( - groupId: 'test-group-id', - )); + smokeTest( + 'join_group', + () => analytics.logJoinGroup( + groupId: 'test-group-id', + )); - smokeTest('level_up', () => analytics.logLevelUp( - level: 56, - )); + smokeTest( + 'level_up', + () => analytics.logLevelUp( + level: 56, + )); smokeTest('login', () => analytics.logLogin()); - smokeTest('post_score', () => analytics.logPostScore( - score: 34, - )); - - smokeTest('present_offer', () => analytics.logPresentOffer( - itemId: 'test-id', - itemName: 'test-name', - itemCategory: 'test-category', - quantity: 5, - )); + smokeTest( + 'post_score', + () => analytics.logPostScore( + score: 34, + )); + + smokeTest( + 'present_offer', + () => analytics.logPresentOffer( + itemId: 'test-id', + itemName: 'test-name', + itemCategory: 'test-category', + quantity: 5, + )); smokeTest('purchase_refund', () => analytics.logPurchaseRefund()); - smokeTest('search', () => analytics.logSearch( - searchTerm: 'test search term', - )); - - smokeTest('select_content', () => analytics.logSelectContent( - contentType: 'test content type', - itemId: 'test item id', - )); - - smokeTest('share', () => analytics.logShare( - contentType: 'test content type', - itemId: 'test item id', - )); - - smokeTest('sign_up', () => analytics.logSignUp( - signUpMethod: 'test sign-up method', - )); - - smokeTest('spend_virtual_currency', () => analytics.logSpendVirtualCurrency( - itemName: 'test-item-name', - virtualCurrencyName: 'bitcoin', - value: 345, - )); + smokeTest( + 'search', + () => analytics.logSearch( + searchTerm: 'test search term', + )); + + smokeTest( + 'select_content', + () => analytics.logSelectContent( + contentType: 'test content type', + itemId: 'test item id', + )); + + smokeTest( + 'share', + () => analytics.logShare( + contentType: 'test content type', + itemId: 'test item id', + )); + + smokeTest( + 'sign_up', + () => analytics.logSignUp( + signUpMethod: 'test sign-up method', + )); + + smokeTest( + 'spend_virtual_currency', + () => analytics.logSpendVirtualCurrency( + itemName: 'test-item-name', + virtualCurrencyName: 'bitcoin', + value: 345, + )); smokeTest('tutorial_begin', () => analytics.logTutorialBegin()); smokeTest('tutorial_complete', () => analytics.logTutorialComplete()); - smokeTest('unlock_achievement', () => analytics.logUnlockAchievement( - id: 'firebase analytics api coverage', - )); - - smokeTest('view_item', () => analytics.logViewItem( - itemId: 'test-id', - itemName: 'test-name', - itemCategory: 'test-category', - )); - - smokeTest('view_item_list', () => analytics.logViewItemList( - itemCategory: 'test-category', - )); - - smokeTest('view_search_results', () => analytics.logViewSearchResults( - searchTerm: 'test search term', - )); - - void testRequiresValueAndCurrencyTogether(String methodName, Future testFn()) { + smokeTest( + 'unlock_achievement', + () => analytics.logUnlockAchievement( + id: 'firebase analytics api coverage', + )); + + smokeTest( + 'view_item', + () => analytics.logViewItem( + itemId: 'test-id', + itemName: 'test-name', + itemCategory: 'test-category', + )); + + smokeTest( + 'view_item_list', + () => analytics.logViewItemList( + itemCategory: 'test-category', + )); + + smokeTest( + 'view_search_results', + () => analytics.logViewSearchResults( + searchTerm: 'test search term', + )); + + void testRequiresValueAndCurrencyTogether( + String methodName, Future testFn()) { test('$methodName requires value and currency together', () async { try { testFn(); fail('Expected ArgumentError'); - } on ArgumentError catch(error) { + } on ArgumentError catch (error) { expect(error.message, valueAndCurrencyMustBeTogetherError); } }); @@ -325,4 +375,4 @@ void main() { }); } -class MockPlatformChannel extends Mock implements MethodChannel { } +class MockPlatformChannel extends Mock implements MethodChannel {} diff --git a/packages/firebase_auth/example/lib/main.dart b/packages/firebase_auth/example/lib/main.dart index 451fcee4ef66..09069d17e8f9 100755 --- a/packages/firebase_auth/example/lib/main.dart +++ b/packages/firebase_auth/example/lib/main.dart @@ -61,7 +61,8 @@ class _MyHomePageState extends State { Future _testSignInWithGoogle() async { final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); - final GoogleSignInAuthentication googleAuth = await googleUser.authentication; + final GoogleSignInAuthentication googleAuth = + await googleUser.authentication; final FirebaseUser user = await _auth.signInWithGoogle( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, @@ -81,30 +82,26 @@ class _MyHomePageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ new MaterialButton( - child: const Text('Test signInAnonymously'), - onPressed: () { - setState(() { - _message = _testSignInAnonymously(); - }); - } - ), + child: const Text('Test signInAnonymously'), + onPressed: () { + setState(() { + _message = _testSignInAnonymously(); + }); + }), new MaterialButton( - child: const Text('Test signInWithGoogle'), - onPressed: () { - setState(() { - _message = _testSignInWithGoogle(); - }); - } - ), + child: const Text('Test signInWithGoogle'), + onPressed: () { + setState(() { + _message = _testSignInWithGoogle(); + }); + }), new FutureBuilder( - future: _message, - builder: (_, AsyncSnapshot snapshot) { - return new Text( - snapshot.data ?? '', - style: const TextStyle(color: const Color.fromARGB(255, 0, 155, 0)) - ); - } - ), + future: _message, + builder: (_, AsyncSnapshot snapshot) { + return new Text(snapshot.data ?? '', + style: const TextStyle( + color: const Color.fromARGB(255, 0, 155, 0))); + }), ], ), ); diff --git a/packages/firebase_auth/lib/firebase_auth.dart b/packages/firebase_auth/lib/firebase_auth.dart index 6fbf228e7d2d..bcf513885cde 100755 --- a/packages/firebase_auth/lib/firebase_auth.dart +++ b/packages/firebase_auth/lib/firebase_auth.dart @@ -37,9 +37,10 @@ class UserInfo { class FirebaseUser extends UserInfo { final List providerData; FirebaseUser._(Map data) - : providerData = data['providerData'] - .map((Map info) => new UserInfo._(info)).toList(), - super._(data); + : providerData = data['providerData'] + .map((Map info) => new UserInfo._(info)) + .toList(), + super._(data); // Returns true if the user is anonymous; that is, the user account was // created with signInAnonymously() and has not been linked to another @@ -80,7 +81,8 @@ class FirebaseAuth { /// FIRAuthErrorCodeOperationNotAllowed - Indicates that anonymous accounts are not enabled. Enable them in the Auth section of the Firebase console. /// See FIRAuthErrors for a list of error codes that are common to all API methods. Future signInAnonymously() async { - final Map data = await _channel.invokeMethod('signInAnonymously'); + final Map data = + await _channel.invokeMethod('signInAnonymously'); _currentUser = new FirebaseUser._(data); return _currentUser; } diff --git a/packages/firebase_auth/test/firebase_auth_test.dart b/packages/firebase_auth/test/firebase_auth_test.dart index 58ab6c11e256..d223aef11918 100755 --- a/packages/firebase_auth/test/firebase_auth_test.dart +++ b/packages/firebase_auth/test/firebase_auth_test.dart @@ -22,7 +22,8 @@ void main() { setUp(() { final MockPlatformChannel mockChannel = new MockPlatformChannel(); - when(mockChannel.invokeMethod('signInAnonymously')).thenAnswer((Invocation invocation) { + when(mockChannel.invokeMethod('signInAnonymously')) + .thenAnswer((Invocation invocation) { return { 'isAnonymous': true, 'isEmailVerified': false, @@ -58,4 +59,4 @@ void main() { }); } -class MockPlatformChannel extends Mock implements MethodChannel { } +class MockPlatformChannel extends Mock implements MethodChannel {} diff --git a/packages/firebase_database/example/lib/main.dart b/packages/firebase_database/example/lib/main.dart index 3cc69dfc5585..c7600f2e6df9 100755 --- a/packages/firebase_database/example/lib/main.dart +++ b/packages/firebase_database/example/lib/main.dart @@ -30,10 +30,10 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { int _counter; - final DatabaseReference _counterRef = FirebaseDatabase.instance.reference() - .child('counter'); - final DatabaseReference _messagesRef = FirebaseDatabase.instance.reference() - .child('messages'); + final DatabaseReference _counterRef = + FirebaseDatabase.instance.reference().child('counter'); + final DatabaseReference _messagesRef = + FirebaseDatabase.instance.reference().child('messages'); StreamSubscription _counterSubscription; StreamSubscription _messagesSubscription; bool _anchorToBottom = false; @@ -69,7 +69,9 @@ class _MyHomePageState extends State { _counter = (snapshot.value ?? 0) + 1; }); _counterRef.set(_counter); - _messagesRef.push().set({ _kTestKey: '$_kTestValue $_counter' }); + _messagesRef + .push() + .set({_kTestKey: '$_kTestValue $_counter'}); } @override @@ -82,17 +84,18 @@ class _MyHomePageState extends State { children: [ new Flexible( child: new Center( - child: new Text( // ignore: prefer_const_constructors + child: new Text( + // ignore: prefer_const_constructors 'Button tapped $_counter time${ _counter == 1 ? '' : 's' }.\n\n' - 'This includes all devices, ever.', + 'This includes all devices, ever.', ), ), ), new ListTile( leading: new Checkbox( onChanged: (bool value) { - setState(() { - _anchorToBottom = value; + setState(() { + _anchorToBottom = value; }); }, value: _anchorToBottom, @@ -104,8 +107,11 @@ class _MyHomePageState extends State { key: new ValueKey(_anchorToBottom), query: _messagesRef, reverse: _anchorToBottom, - sort: _anchorToBottom ? (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key) : null, - itemBuilder: (BuildContext context, DataSnapshot snapshot, Animation animation) { + sort: _anchorToBottom + ? (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key) + : null, + itemBuilder: (BuildContext context, DataSnapshot snapshot, + Animation animation) { return new SizeTransition( sizeFactor: animation, child: new Text(snapshot.value.toString()), @@ -113,7 +119,6 @@ class _MyHomePageState extends State { }, ), ), - ], ), floatingActionButton: new FloatingActionButton( diff --git a/packages/firebase_database/lib/src/database_reference.dart b/packages/firebase_database/lib/src/database_reference.dart index 1bf8e1e6086d..70087aaf7cb2 100644 --- a/packages/firebase_database/lib/src/database_reference.dart +++ b/packages/firebase_database/lib/src/database_reference.dart @@ -14,28 +14,23 @@ part of firebase_database; /// `DatabaseReference`s (ie. `child`). class DatabaseReference extends Query { DatabaseReference._(FirebaseDatabase database, List pathComponents) - : super._(database: database, pathComponents: pathComponents); + : super._(database: database, pathComponents: pathComponents); /// Gets a DatabaseReference for the location at the specified relative /// path. The relative path can either be a simple child key (e.g. ‘fred’) or /// a deeper slash-separated path (e.g. ‘fred/name/first’). DatabaseReference child(String path) { - return new DatabaseReference._( - _database, - (new List.from(_pathComponents)..addAll(path.split('/'))) - ); + return new DatabaseReference._(_database, + (new List.from(_pathComponents)..addAll(path.split('/')))); } /// Gets a DatabaseReference for the parent location. If this instance /// refers to the root of your Firebase Database, it has no parent, and /// therefore parent() will return null. DatabaseReference parent() { - if (_pathComponents.isEmpty) - return null; + if (_pathComponents.isEmpty) return null; return new DatabaseReference._( - _database, - (new List.from(_pathComponents)..removeLast()) - ); + _database, (new List.from(_pathComponents)..removeLast())); } /// Gets a FIRDatabaseReference for the root location. @@ -56,7 +51,8 @@ class DatabaseReference extends Query { /// chronologically-sorted. DatabaseReference push() { final String key = PushIdGenerator.generatePushChildName(); - final List childPath = new List.from(_pathComponents)..add(key); + final List childPath = new List.from(_pathComponents) + ..add(key); return new DatabaseReference._(_database, childPath); } @@ -72,10 +68,10 @@ class DatabaseReference extends Query { /// /// Passing null for the new value means all data at this location or any /// child location will be deleted. - Future set(dynamic value, { dynamic priority }) { + Future set(dynamic value, {dynamic priority}) { return _database._channel.invokeMethod( 'DatabaseReference#set', - { 'path': path, 'value': value, 'priority': priority }, + {'path': path, 'value': value, 'priority': priority}, ); } @@ -106,7 +102,7 @@ class DatabaseReference extends Query { Future setPriority(dynamic priority) async { return _database._channel.invokeMethod( 'DatabaseReference#setPriority', - { 'path': path, 'priority': priority }, + {'path': path, 'priority': priority}, ); } @@ -120,6 +116,9 @@ class DatabaseReference extends Query { /// remove() is equivalent to calling set(null) Future remove() => set(null); } + class ServerValue { - static const Map timestamp = const {'.sv' : 'timestamp'}; + static const Map timestamp = const { + '.sv': 'timestamp' + }; } diff --git a/packages/firebase_database/lib/src/firebase_database.dart b/packages/firebase_database/lib/src/firebase_database.dart index 2b66f610b3b3..d2ce9307b6a2 100644 --- a/packages/firebase_database/lib/src/firebase_database.dart +++ b/packages/firebase_database/lib/src/firebase_database.dart @@ -12,7 +12,8 @@ class FirebaseDatabase { 'plugins.flutter.io/firebase_database', ); - static final Map> _observers = >{}; + static final Map> _observers = + >{}; FirebaseDatabase._() { _channel.setMethodCallHandler((MethodCall call) { @@ -46,7 +47,7 @@ class FirebaseDatabase { Future setPersistenceEnabled(bool enabled) { return _channel.invokeMethod( "FirebaseDatabase#setPersistenceEnabled", - { 'enabled': enabled }, + {'enabled': enabled}, ); } @@ -63,7 +64,7 @@ class FirebaseDatabase { Future setPersistenceCacheSizeBytes(int cacheSize) { return _channel.invokeMethod( "FirebaseDatabase#setPersistenceCacheSizeBytes", - { 'cacheSize': cacheSize }, + {'cacheSize': cacheSize}, ); } diff --git a/packages/firebase_database/lib/src/utils/push_id_generator.dart b/packages/firebase_database/lib/src/utils/push_id_generator.dart index 0d901eb5fe88..888953c14dac 100644 --- a/packages/firebase_database/lib/src/utils/push_id_generator.dart +++ b/packages/firebase_database/lib/src/utils/push_id_generator.dart @@ -14,7 +14,6 @@ import 'dart:math'; /// This code is based on a Firebase blog post and ported to Dart. /// https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html class PushIdGenerator { - static const String PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; diff --git a/packages/firebase_database/lib/ui/firebase_animated_list.dart b/packages/firebase_database/lib/ui/firebase_animated_list.dart index b4dd0344c6f4..04839415fccd 100755 --- a/packages/firebase_database/lib/ui/firebase_animated_list.dart +++ b/packages/firebase_database/lib/ui/firebase_animated_list.dart @@ -32,7 +32,8 @@ class FirebaseAnimatedList extends StatefulWidget { this.shrinkWrap: false, this.padding, this.duration: const Duration(milliseconds: 300), - }) : super(key: key) { + }) + : super(key: key) { assert(itemBuilder != null); } @@ -131,7 +132,8 @@ class FirebaseAnimatedList extends StatefulWidget { } class FirebaseAnimatedListState extends State { - final GlobalKey _animatedListKey = new GlobalKey(); + final GlobalKey _animatedListKey = + new GlobalKey(); List _model; bool _loaded = false; @@ -160,8 +162,7 @@ class FirebaseAnimatedListState extends State { } void _onChildAdded(int index, DataSnapshot snapshot) { - if (!_loaded) - return; // AnimatedList is not created yet + if (!_loaded) return; // AnimatedList is not created yet _animatedListKey.currentState.insertItem(index, duration: widget.duration); } @@ -193,14 +194,14 @@ class FirebaseAnimatedListState extends State { }); } - Widget _buildItem(BuildContext context, int index, Animation animation) { + Widget _buildItem( + BuildContext context, int index, Animation animation) { return widget.itemBuilder(context, _model[index], animation); } @override Widget build(BuildContext context) { - if (!_loaded) - return widget.defaultChild ?? new Container(); + if (!_loaded) return widget.defaultChild ?? new Container(); return new AnimatedList( key: _animatedListKey, itemBuilder: _buildItem, diff --git a/packages/firebase_database/lib/ui/firebase_list.dart b/packages/firebase_database/lib/ui/firebase_list.dart index b960c9e7f75d..af7e99064373 100644 --- a/packages/firebase_database/lib/ui/firebase_list.dart +++ b/packages/firebase_database/lib/ui/firebase_list.dart @@ -10,11 +10,13 @@ import '../firebase_database.dart' show DataSnapshot, Event, Query; import 'utils/stream_subscriber_mixin.dart'; typedef void ChildCallback(int index, DataSnapshot snapshot); -typedef void ChildMovedCallback(int fromIndex, int toIndex, DataSnapshot snapshot); +typedef void ChildMovedCallback( + int fromIndex, int toIndex, DataSnapshot snapshot); typedef void ValueCallback(DataSnapshot snapshot); /// Sorts the results of `query` on the client side using `DataSnapshot.key`. -class FirebaseList extends ListBase with StreamSubscriberMixin { +class FirebaseList extends ListBase + with StreamSubscriberMixin { FirebaseList({ @required this.query, this.onChildAdded, @@ -119,4 +121,3 @@ class FirebaseList extends ListBase with StreamSubscriberMixin with StreamSubscriberMixin { +class FirebaseSortedList extends ListBase + with StreamSubscriberMixin { FirebaseSortedList({ @required this.query, @required this.comparator, @@ -78,7 +79,8 @@ class FirebaseSortedList extends ListBase with StreamSubscriberMix } void _onChildRemoved(Event event) { - final DataSnapshot snapshot = _snapshots.firstWhere((DataSnapshot snapshot) { + final DataSnapshot snapshot = + _snapshots.firstWhere((DataSnapshot snapshot) { return snapshot.key == event.snapshot.key; }); final int index = _snapshots.indexOf(snapshot); @@ -87,7 +89,8 @@ class FirebaseSortedList extends ListBase with StreamSubscriberMix } void _onChildChanged(Event event) { - final DataSnapshot snapshot = _snapshots.firstWhere((DataSnapshot snapshot) { + final DataSnapshot snapshot = + _snapshots.firstWhere((DataSnapshot snapshot) { return snapshot.key == event.snapshot.key; }); final int index = _snapshots.indexOf(snapshot); diff --git a/packages/firebase_database/lib/ui/utils/stream_subscriber_mixin.dart b/packages/firebase_database/lib/ui/utils/stream_subscriber_mixin.dart index 152e82cad898..d36189d8feaa 100644 --- a/packages/firebase_database/lib/ui/utils/stream_subscriber_mixin.dart +++ b/packages/firebase_database/lib/ui/utils/stream_subscriber_mixin.dart @@ -18,6 +18,7 @@ abstract class StreamSubscriberMixin { /// Cancels all streams that were previously added with listen(). void dispose() { - _subscriptions.forEach((StreamSubscription subscription) => subscription.cancel()); + _subscriptions + .forEach((StreamSubscription subscription) => subscription.cancel()); } -} \ No newline at end of file +} diff --git a/packages/firebase_database/test/firebase_database_test.dart b/packages/firebase_database/test/firebase_database_test.dart index 1da806016e4c..6a5d5a7856fb 100755 --- a/packages/firebase_database/test/firebase_database_test.dart +++ b/packages/firebase_database/test/firebase_database_test.dart @@ -12,8 +12,7 @@ import 'package:flutter/services.dart'; import 'package:firebase_database/firebase_database.dart'; void main() { - group('$FirebaseDatabase', () - { + group('$FirebaseDatabase', () { const MethodChannel channel = const MethodChannel( 'plugins.flutter.io/firebase_database', ); @@ -36,41 +35,53 @@ void main() { test('setPersistenceEnabled', () async { await database.setPersistenceEnabled(false); await database.setPersistenceEnabled(true); - expect(log, equals([ - new MethodCall('FirebaseDatabase#setPersistenceEnabled', { 'enabled': false }), - new MethodCall('FirebaseDatabase#setPersistenceEnabled', { 'enabled': true }), - ])); + expect( + log, + equals([ + new MethodCall('FirebaseDatabase#setPersistenceEnabled', + {'enabled': false}), + new MethodCall('FirebaseDatabase#setPersistenceEnabled', + {'enabled': true}), + ])); }); test('setPersistentCacheSizeBytes', () async { await database.setPersistenceCacheSizeBytes(42); - expect(log, equals([ - new MethodCall( - 'FirebaseDatabase#setPersistenceCacheSizeBytes', - { 'cacheSize': 42 }, - ), - ])); + expect( + log, + equals([ + new MethodCall( + 'FirebaseDatabase#setPersistenceCacheSizeBytes', + {'cacheSize': 42}, + ), + ])); }); test('goOnline', () async { await database.goOnline(); - expect(log, equals([ - const MethodCall('FirebaseDatabase#goOnline'), - ])); + expect( + log, + equals([ + const MethodCall('FirebaseDatabase#goOnline'), + ])); }); test('goOffline', () async { await database.goOffline(); - expect(log, equals([ - const MethodCall('FirebaseDatabase#goOffline'), - ])); + expect( + log, + equals([ + const MethodCall('FirebaseDatabase#goOffline'), + ])); }); test('purgeOutstandingWrites', () async { await database.purgeOutstandingWrites(); - expect(log, equals([ - const MethodCall('FirebaseDatabase#purgeOutstandingWrites'), - ])); + expect( + log, + equals([ + const MethodCall('FirebaseDatabase#purgeOutstandingWrites'), + ])); }); group('$DatabaseReference', () { @@ -79,57 +90,78 @@ void main() { final int priority = 42; await database.reference().child('foo').set(value); await database.reference().child('bar').set(value, priority: priority); - expect(log, equals([ - new MethodCall( - 'DatabaseReference#set', - { 'path': 'foo', 'value': value, 'priority': null }, - ), - new MethodCall( - 'DatabaseReference#set', - { 'path': 'bar', 'value': value, 'priority': priority }, - ), - ])); + expect( + log, + equals([ + new MethodCall( + 'DatabaseReference#set', + { + 'path': 'foo', + 'value': value, + 'priority': null + }, + ), + new MethodCall( + 'DatabaseReference#set', + { + 'path': 'bar', + 'value': value, + 'priority': priority + }, + ), + ])); }); test('setPriority', () async { final int priority = 42; await database.reference().child('foo').setPriority(priority); - expect(log, equals([ - new MethodCall( - 'DatabaseReference#setPriority', - { 'path': 'foo', 'priority': priority }, - ), - ])); + expect( + log, + equals([ + new MethodCall( + 'DatabaseReference#setPriority', + {'path': 'foo', 'priority': priority}, + ), + ])); }); }); group('$Query', () { // TODO(jackson): Write more tests for queries test('observing', () async { - final Query query = database.reference().child('foo').orderByChild('bar'); - final StreamSubscription subscription = query.onValue.listen((_) {}); + final Query query = + database.reference().child('foo').orderByChild('bar'); + final StreamSubscription subscription = + query.onValue.listen((_) {}); await query.keepSynced(true); subscription.cancel(); final Map expectedParameters = { 'orderBy': 'child', 'orderByChildKey': 'bar', }; - expect(log, equals([ - new MethodCall( - 'Query#observe', - { 'path': 'foo', - 'parameters': expectedParameters, - 'eventType': '_EventType.value' - }, - ), - new MethodCall( - 'Query#keepSynced', - { 'path': 'foo', 'parameters': expectedParameters, 'value': true}, - ), - ])); + expect( + log, + equals([ + new MethodCall( + 'Query#observe', + { + 'path': 'foo', + 'parameters': expectedParameters, + 'eventType': '_EventType.value' + }, + ), + new MethodCall( + 'Query#keepSynced', + { + 'path': 'foo', + 'parameters': expectedParameters, + 'value': true + }, + ), + ])); }); }); }); } -class MockPlatformChannel extends Mock implements MethodChannel { } \ No newline at end of file +class MockPlatformChannel extends Mock implements MethodChannel {} diff --git a/packages/firebase_messaging/lib/firebase_messaging.dart b/packages/firebase_messaging/lib/firebase_messaging.dart index c10bf8ab8496..fbdafff773d4 100644 --- a/packages/firebase_messaging/lib/firebase_messaging.dart +++ b/packages/firebase_messaging/lib/firebase_messaging.dart @@ -79,7 +79,9 @@ class FirebaseMessaging { /// Returns the FCM token. Future getToken() { - return _token != null ? new Future.value(_token) : onTokenRefresh.first; + return _token != null + ? new Future.value(_token) + : onTokenRefresh.first; } /// Subscribe to topic in background. diff --git a/packages/firebase_storage/example/lib/main.dart b/packages/firebase_storage/example/lib/main.dart index a1088d067dbb..162605f1839e 100755 --- a/packages/firebase_storage/example/lib/main.dart +++ b/packages/firebase_storage/example/lib/main.dart @@ -40,7 +40,8 @@ class _MyHomePageState extends State { file.writeAsString(kTestString); assert(await file.readAsString() == kTestString); final String rand = "${new Random().nextInt(10000)}"; - final StorageReference ref = FirebaseStorage.instance.ref().child("foo$rand.txt"); + final StorageReference ref = + FirebaseStorage.instance.ref().child("foo$rand.txt"); final StorageUploadTask uploadTask = ref.put(file); final Uri downloadUrl = (await uploadTask.future).downloadUrl; final http.Response downloadData = await http.get(downloadUrl); @@ -59,12 +60,13 @@ class _MyHomePageState extends State { child: new Column( mainAxisSize: MainAxisSize.min, children: [ - _fileContents == null ? - const Text('Press the button to upload a file') : - new Text( - 'Success!\n\nFile contents: "$_fileContents"', - style: const TextStyle(color: const Color.fromARGB(255, 0, 155, 0)), - ) + _fileContents == null + ? const Text('Press the button to upload a file') + : new Text( + 'Success!\n\nFile contents: "$_fileContents"', + style: const TextStyle( + color: const Color.fromARGB(255, 0, 155, 0)), + ) ], ), ), diff --git a/packages/firebase_storage/lib/firebase_storage.dart b/packages/firebase_storage/lib/firebase_storage.dart index 0861cea591e9..e66fd850b1d3 100755 --- a/packages/firebase_storage/lib/firebase_storage.dart +++ b/packages/firebase_storage/lib/firebase_storage.dart @@ -22,12 +22,14 @@ class StorageReference { final List _pathComponents; StorageReference child(String path) { - final List childPath = new List.from(_pathComponents)..addAll(path.split("/")); + final List childPath = new List.from(_pathComponents) + ..addAll(path.split("/")); return new StorageReference._(childPath); } StorageUploadTask put(File file) { - final StorageUploadTask task = new StorageUploadTask._(file, _pathComponents.join("/")); + final StorageUploadTask task = + new StorageUploadTask._(file, _pathComponents.join("/")); task._start(); return task; } @@ -38,22 +40,24 @@ class StorageUploadTask { final File file; final String path; - Completer _completer = new Completer(); + Completer _completer = + new Completer(); Future get future => _completer.future; Future _start() async { final String downloadUrl = await FirebaseStorage._channel.invokeMethod( - "StorageReference#putFile", - { - 'filename': file.absolute.path, - 'path': path, - }, + "StorageReference#putFile", + { + 'filename': file.absolute.path, + 'path': path, + }, ); - _completer.complete(new UploadTaskSnapshot(downloadUrl: Uri.parse(downloadUrl))); + _completer + .complete(new UploadTaskSnapshot(downloadUrl: Uri.parse(downloadUrl))); } } class UploadTaskSnapshot { - UploadTaskSnapshot({ this.downloadUrl }); + UploadTaskSnapshot({this.downloadUrl}); final Uri downloadUrl; } diff --git a/packages/google_sign_in/example/lib/main.dart b/packages/google_sign_in/example/lib/main.dart index d5fa7d019486..60ef8e99cf01 100755 --- a/packages/google_sign_in/example/lib/main.dart +++ b/packages/google_sign_in/example/lib/main.dart @@ -18,10 +18,10 @@ GoogleSignIn _googleSignIn = new GoogleSignIn( void main() { runApp( - new MaterialApp( - title: 'Google Sign In', - home: new SignInDemo(), - ), + new MaterialApp( + title: 'Google Sign In', + home: new SignInDemo(), + ), ); } @@ -53,9 +53,9 @@ class SignInDemoState extends State { _contactText = "Loading contact info..."; }); final http.Response response = await http.get( - 'https://people.googleapis.com/v1/people/me/connections' - '?requestMask.includeField=person.names', - headers: await _currentUser.authHeaders, + 'https://people.googleapis.com/v1/people/me/connections' + '?requestMask.includeField=person.names', + headers: await _currentUser.authHeaders, ); if (response.statusCode != 200) { setState(() { @@ -79,13 +79,13 @@ class SignInDemoState extends State { String _pickFirstNamedContact(Map data) { final List> connections = data['connections']; final Map contact = connections?.firstWhere( - (Map contact) => contact['names'] != null, - orElse: () => null, + (Map contact) => contact['names'] != null, + orElse: () => null, ); if (contact != null) { final Map name = contact['names'].firstWhere( - (Map name) => name['displayName'] != null, - orElse: () => null, + (Map name) => name['displayName'] != null, + orElse: () => null, ); if (name != null) { return name['displayName']; @@ -109,35 +109,35 @@ class SignInDemoState extends State { Widget _buildBody() { if (_currentUser != null) { return new Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - new ListTile( - leading: new GoogleUserCircleAvatar(_currentUser.photoUrl), - title: new Text(_currentUser.displayName), - subtitle: new Text(_currentUser.email), - ), - const Text("Signed in successfully."), - new Text(_contactText), - new RaisedButton( - child: const Text('SIGN OUT'), - onPressed: _handleSignOut, - ), - new RaisedButton( - child: const Text('REFRESH'), - onPressed: _handleGetContact, - ), - ], + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + new ListTile( + leading: new GoogleUserCircleAvatar(_currentUser.photoUrl), + title: new Text(_currentUser.displayName), + subtitle: new Text(_currentUser.email), + ), + const Text("Signed in successfully."), + new Text(_contactText), + new RaisedButton( + child: const Text('SIGN OUT'), + onPressed: _handleSignOut, + ), + new RaisedButton( + child: const Text('REFRESH'), + onPressed: _handleGetContact, + ), + ], ); } else { return new Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - const Text("You are not currently signed in."), - new RaisedButton( - child: const Text('SIGN IN'), - onPressed: _handleSignIn, - ), - ], + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + const Text("You are not currently signed in."), + new RaisedButton( + child: const Text('SIGN IN'), + onPressed: _handleSignIn, + ), + ], ); } } @@ -146,11 +146,11 @@ class SignInDemoState extends State { Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( - title: const Text('Google Sign In'), + title: const Text('Google Sign In'), ), body: new ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), + constraints: const BoxConstraints.expand(), + child: _buildBody(), )); } } diff --git a/packages/google_sign_in/lib/google_sign_in.dart b/packages/google_sign_in/lib/google_sign_in.dart index fa2b0054b94c..d48cf9e9c59d 100755 --- a/packages/google_sign_in/lib/google_sign_in.dart +++ b/packages/google_sign_in/lib/google_sign_in.dart @@ -44,7 +44,8 @@ class GoogleSignInAccount { throw new StateError('User is no longer signed in.'); } - final Map response = await _googleSignIn._channel.invokeMethod( + final Map response = + await _googleSignIn._channel.invokeMethod( 'getTokens', {'email': email}, ); @@ -144,7 +145,10 @@ class GoogleSignIn { // If after the last completed call currentUser is not null and requested // method is a sign in method, re-use the same authenticated user // instead of making extra call to the native side. - const List kSignInMethods = const ['signIn', 'signInSilently']; + const List kSignInMethods = const [ + 'signIn', + 'signInSilently' + ]; if (kSignInMethods.contains(method) && _currentUser != null) { completer.complete(_currentUser); } else { @@ -214,7 +218,8 @@ class GoogleUserCircleAvatar extends StatelessWidget { String _sizedProfileImageUrl(double size) { if (_primaryProfileImageUrl == null) return null; final Uri profileUri = Uri.parse(_primaryProfileImageUrl); - final List pathSegments = new List.from(profileUri.pathSegments); + final List pathSegments = + new List.from(profileUri.pathSegments); pathSegments.remove("s1337"); // placeholder value added by iOS plugin return new Uri( scheme: profileUri.scheme, @@ -241,7 +246,8 @@ class GoogleUserCircleAvatar extends StatelessWidget { class _MethodCompleter { final String method; - final Completer _completer = new Completer(); + final Completer _completer = + new Completer(); _MethodCompleter(this.method); diff --git a/packages/google_sign_in/test/google_sign_in_test.dart b/packages/google_sign_in/test/google_sign_in_test.dart index 2e80e42c44c9..2bafbb3a9fc2 100755 --- a/packages/google_sign_in/test/google_sign_in_test.dart +++ b/packages/google_sign_in/test/google_sign_in_test.dart @@ -48,7 +48,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signInSilently'), ])); }); @@ -59,7 +60,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signIn'), ])); }); @@ -70,7 +72,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signOut'), ])); }); @@ -81,7 +84,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('disconnect'), ])); }); @@ -93,13 +97,15 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('disconnect'), ])); }); test('concurrent calls of the same method trigger sign in once', () async { - final List> futures = >[ + final List> futures = + >[ googleSignIn.signInSilently(), googleSignIn.signInSilently(), ]; @@ -107,11 +113,15 @@ void main() { reason: 'Must return new Future'); final List users = await Future.wait(futures); expect(googleSignIn.currentUser, isNotNull); - expect(users, [googleSignIn.currentUser, googleSignIn.currentUser]); + expect(users, [ + googleSignIn.currentUser, + googleSignIn.currentUser + ]); expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signInSilently'), ])); }); @@ -124,14 +134,16 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signInSilently'), const MethodCall('signIn'), ])); }); test('concurrent calls of different signIn methods', () async { - final List> futures = >[ + final List> futures = + >[ googleSignIn.signInSilently(), googleSignIn.signIn(), ]; @@ -140,7 +152,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signInSilently'), ])); expect(users.first, users.last, reason: 'Must return the same user'); @@ -155,7 +168,8 @@ void main() { }); test('signOut/disconnect methods always trigger native calls', () async { - final List> futures = >[ + final List> futures = + >[ googleSignIn.signOut(), googleSignIn.signOut(), googleSignIn.disconnect(), @@ -165,7 +179,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signOut'), const MethodCall('signOut'), const MethodCall('disconnect'), @@ -174,7 +189,8 @@ void main() { }); test('queue of many concurrent calls', () async { - final List> futures = >[ + final List> futures = + >[ googleSignIn.signInSilently(), googleSignIn.signOut(), googleSignIn.signIn(), @@ -184,7 +200,8 @@ void main() { expect( log, equals([ - new MethodCall('init', {'scopes': [], 'hostedDomain': null}), + new MethodCall('init', + {'scopes': [], 'hostedDomain': null}), const MethodCall('signInSilently'), const MethodCall('signOut'), const MethodCall('signIn'), diff --git a/packages/image_picker/example/lib/main.dart b/packages/image_picker/example/lib/main.dart index 672920886cca..0a8d42347051 100755 --- a/packages/image_picker/example/lib/main.dart +++ b/packages/image_picker/example/lib/main.dart @@ -41,17 +41,15 @@ class _MyHomePageState extends State { title: const Text('Image Picker Example'), ), body: new Center( - child: new FutureBuilder( - future: _imageFile, - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.done) { - return new Image.file(snapshot.data); - } else { - return const Text('You have not yet picked an image.'); - } - } - ) - ), + child: new FutureBuilder( + future: _imageFile, + builder: (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.connectionState == ConnectionState.done) { + return new Image.file(snapshot.data); + } else { + return const Text('You have not yet picked an image.'); + } + })), floatingActionButton: new FloatingActionButton( onPressed: () { setState(() { diff --git a/packages/image_picker/lib/image_picker.dart b/packages/image_picker/lib/image_picker.dart index 132c7cca28ad..5c66208e08dc 100755 --- a/packages/image_picker/lib/image_picker.dart +++ b/packages/image_picker/lib/image_picker.dart @@ -8,8 +8,7 @@ import 'dart:io'; import 'package:flutter/services.dart'; class ImagePicker { - static const MethodChannel _channel = - const MethodChannel('image_picker'); + static const MethodChannel _channel = const MethodChannel('image_picker'); // Returns the URL of the picked image static Future pickImage() async { diff --git a/packages/path_provider/example/lib/main.dart b/packages/path_provider/example/lib/main.dart index 15aa2fc39efb..37a446f21fed 100644 --- a/packages/path_provider/example/lib/main.dart +++ b/packages/path_provider/example/lib/main.dart @@ -46,7 +46,6 @@ class _MyHomePageState extends State { Widget _buildDirectory( BuildContext context, AsyncSnapshot snapshot) { - Text text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -112,24 +111,23 @@ class _MyHomePageState extends State { child: new FutureBuilder( future: _appDocumentsDirectory, builder: _buildDirectory), ), - new Column( - children : [ - new Padding( - padding: const EdgeInsets.all(16.0), - child: new RaisedButton( - child: new Text('${Platform.isIOS ? + new Column(children: [ + new Padding( + padding: const EdgeInsets.all(16.0), + child: new RaisedButton( + child: new Text('${Platform.isIOS ? "External directories are unavailable " "on iOS": "Get External Storage Directory" }'), - onPressed: Platform.isIOS ? null : - _requestExternalStorageDirectory, - ), + onPressed: + Platform.isIOS ? null : _requestExternalStorageDirectory, ), - ] - ), + ), + ]), new Expanded( child: new FutureBuilder( - future: _externalDocumentsDirectory, builder: _buildDirectory), + future: _externalDocumentsDirectory, + builder: _buildDirectory), ), ], ), diff --git a/packages/path_provider/lib/path_provider.dart b/packages/path_provider/lib/path_provider.dart index acbf8f042d45..95857f29e60c 100644 --- a/packages/path_provider/lib/path_provider.dart +++ b/packages/path_provider/lib/path_provider.dart @@ -7,53 +7,51 @@ import 'dart:io'; import 'package:flutter/services.dart'; -const MethodChannel _channel = const MethodChannel('plugins.flutter.io/path_provider'); +const MethodChannel _channel = + const MethodChannel('plugins.flutter.io/path_provider'); - /// Path to the temporary directory on the device. - /// - /// Files in this directory may be cleared at any time. This does *not* return - /// a new temporary directory. Instead, the caller is responsible for creating - /// (and cleaning up) files or directories within this directory. This - /// directory is scoped to the calling application. - /// - /// On iOS, this uses the `NSTemporaryDirectory` API. - /// - /// On Android, this uses the `getCacheDir` API on the context. - Future getTemporaryDirectory() async { - final String path = await _channel.invokeMethod('getTemporaryDirectory'); - if (path == null) - return null; - return new Directory(path); - } +/// Path to the temporary directory on the device. +/// +/// Files in this directory may be cleared at any time. This does *not* return +/// a new temporary directory. Instead, the caller is responsible for creating +/// (and cleaning up) files or directories within this directory. This +/// directory is scoped to the calling application. +/// +/// On iOS, this uses the `NSTemporaryDirectory` API. +/// +/// On Android, this uses the `getCacheDir` API on the context. +Future getTemporaryDirectory() async { + final String path = await _channel.invokeMethod('getTemporaryDirectory'); + if (path == null) return null; + return new Directory(path); +} - /// Path to a directory where the application may place files that are private - /// to the application and will only be cleared when the application itself - /// is deleted. - /// - /// On iOS, this uses the `NSDocumentsDirectory` API. - /// - /// On Android, this returns the AppData directory. - Future getApplicationDocumentsDirectory() async { - final String path = await _channel.invokeMethod( - 'getApplicationDocumentsDirectory'); - if (path == null) - return null; - return new Directory(path); - } +/// Path to a directory where the application may place files that are private +/// to the application and will only be cleared when the application itself +/// is deleted. +/// +/// On iOS, this uses the `NSDocumentsDirectory` API. +/// +/// On Android, this returns the AppData directory. +Future getApplicationDocumentsDirectory() async { + final String path = + await _channel.invokeMethod('getApplicationDocumentsDirectory'); + if (path == null) return null; + return new Directory(path); +} - /// Path to a directory where the application may access top level storage. - /// The current operating system should be determined before issuing this - /// function call, as this functionality is only available on Android. - /// - /// On iOS, this function throws an UnsupportedError as it is not possible - /// to access outside the app's sandbox. - /// - /// On Android this returns getExternalStorageDirectory. - Future getExternalStorageDirectory() async { - if (Platform.isIOS) - throw new UnsupportedError("Functionality not available on iOS"); - final String path = await _channel.invokeMethod('getStorageDirectory'); - if (path == null) - return null; - return new Directory(path); - } +/// Path to a directory where the application may access top level storage. +/// The current operating system should be determined before issuing this +/// function call, as this functionality is only available on Android. +/// +/// On iOS, this function throws an UnsupportedError as it is not possible +/// to access outside the app's sandbox. +/// +/// On Android this returns getExternalStorageDirectory. +Future getExternalStorageDirectory() async { + if (Platform.isIOS) + throw new UnsupportedError("Functionality not available on iOS"); + final String path = await _channel.invokeMethod('getStorageDirectory'); + if (path == null) return null; + return new Directory(path); +} diff --git a/packages/path_provider/test/path_provider_test.dart b/packages/path_provider/test/path_provider_test.dart index 4a532696bb89..37de01214a49 100644 --- a/packages/path_provider/test/path_provider_test.dart +++ b/packages/path_provider/test/path_provider_test.dart @@ -9,7 +9,8 @@ import 'package:path_provider/path_provider.dart'; import 'package:test/test.dart'; void main() { - const MethodChannel channel = const MethodChannel('plugins.flutter.io/path_provider'); + const MethodChannel channel = + const MethodChannel('plugins.flutter.io/path_provider'); final List log = []; String response; @@ -25,7 +26,8 @@ void main() { test('getTemporaryDirectory test', () async { response = null; final Directory directory = await getTemporaryDirectory(); - expect(log, equals([const MethodCall('getTemporaryDirectory')])); + expect( + log, equals([const MethodCall('getTemporaryDirectory')])); expect(directory, isNull); }); @@ -34,7 +36,8 @@ void main() { final Directory directory = await getApplicationDocumentsDirectory(); expect( log, - equals([const MethodCall('getApplicationDocumentsDirectory')]), + equals( + [const MethodCall('getApplicationDocumentsDirectory')]), ); expect(directory, isNull); }); diff --git a/packages/share/example/lib/main.dart b/packages/share/example/lib/main.dart index 67747d71ee4b..c6295eca3b96 100644 --- a/packages/share/example/lib/main.dart +++ b/packages/share/example/lib/main.dart @@ -22,32 +22,35 @@ class DemoAppState extends State { return new MaterialApp( title: 'Share Plugin Demo', home: new Scaffold( - appBar: new AppBar( - title: const Text('Share Plugin Demo'), - ), - body: new Padding( - padding: const EdgeInsets.all(24.0), - child: new Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - new TextField( - decoration: const InputDecoration( - labelText: 'Share:', - hintText: 'Enter some text and/or link to share', - ), - maxLines: 4, - onChanged: (String value) => setState(() { text = value; }), - ), - new RaisedButton( - child: const Text('Share'), - onPressed: text.isNotEmpty - ? () { share(text); } - : null, - ), - ], + appBar: new AppBar( + title: const Text('Share Plugin Demo'), ), - ) - ), + body: new Padding( + padding: const EdgeInsets.all(24.0), + child: new Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + new TextField( + decoration: const InputDecoration( + labelText: 'Share:', + hintText: 'Enter some text and/or link to share', + ), + maxLines: 4, + onChanged: (String value) => setState(() { + text = value; + }), + ), + new RaisedButton( + child: const Text('Share'), + onPressed: text.isNotEmpty + ? () { + share(text); + } + : null, + ), + ], + ), + )), ); } } diff --git a/packages/shared_preferences/example/lib/main.dart b/packages/shared_preferences/example/lib/main.dart index 2147f6b4d48d..ec1277ae9491 100644 --- a/packages/shared_preferences/example/lib/main.dart +++ b/packages/shared_preferences/example/lib/main.dart @@ -22,7 +22,7 @@ class MyApp extends StatelessWidget { } class SharedPreferencesDemo extends StatefulWidget { - SharedPreferencesDemo({ Key key }) : super(key: key); + SharedPreferencesDemo({Key key}) : super(key: key); @override SharedPreferencesDemoState createState() => new SharedPreferencesDemoState(); @@ -46,19 +46,19 @@ class SharedPreferencesDemoState extends State { title: const Text("SharedPreferences Demo"), ), body: new Center( - child: new FutureBuilder( - future: _prefs, - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) - return const Text('Loading...'); - final int counter = snapshot.requireData.getInt('counter') ?? 0; - return new Text( // ignore: prefer_const_constructors - 'Button tapped $counter time${ counter == 1 ? '' : 's' }.\n\n' - 'This should persist across restarts.', - ); - } - ) - ), + child: new FutureBuilder( + future: _prefs, + builder: (BuildContext context, + AsyncSnapshot snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) + return const Text('Loading...'); + final int counter = snapshot.requireData.getInt('counter') ?? 0; + return new Text( + // ignore: prefer_const_constructors + 'Button tapped $counter time${ counter == 1 ? '' : 's' }.\n\n' + 'This should persist across restarts.', + ); + })), floatingActionButton: new FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', diff --git a/packages/shared_preferences/lib/shared_preferences.dart b/packages/shared_preferences/lib/shared_preferences.dart index 3c2cc8e9105d..8608b27a9abe 100644 --- a/packages/shared_preferences/lib/shared_preferences.dart +++ b/packages/shared_preferences/lib/shared_preferences.dart @@ -14,14 +14,14 @@ const MethodChannel _kChannel = /// a persistent store for simple data. Data is persisted to disk automatically /// and asynchronously. Use commit() to be notified when a save is successful. class SharedPreferences { - SharedPreferences._(this._preferenceCache); static const String _prefix = 'flutter.'; static SharedPreferences _instance; static Future getInstance() async { if (_instance == null) { - final Map fromSystem = await _kChannel.invokeMethod('getAll'); + final Map fromSystem = + await _kChannel.invokeMethod('getAll'); assert(fromSystem != null); // Strip the flutter. prefix from the returned preferences. final Map preferencesMap = {}; diff --git a/packages/shared_preferences/test/shared_preferences_test.dart b/packages/shared_preferences/test/shared_preferences_test.dart index bd0b8d76ffbb..d3f8af36968e 100755 --- a/packages/shared_preferences/test/shared_preferences_test.dart +++ b/packages/shared_preferences/test/shared_preferences_test.dart @@ -10,8 +10,7 @@ import 'package:flutter/services.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { - group('$SharedPreferences', () - { + group('$SharedPreferences', () { const MethodChannel channel = const MethodChannel( 'plugins.flutter.io/shared_preferences', ); @@ -48,11 +47,14 @@ void main() { }); test('reading', () async { - expect(sharedPreferences.getString('String'), kTestValues['flutter.String']); + expect( + sharedPreferences.getString('String'), kTestValues['flutter.String']); expect(sharedPreferences.getBool('bool'), kTestValues['flutter.bool']); expect(sharedPreferences.getInt('int'), kTestValues['flutter.int']); - expect(sharedPreferences.getDouble('double'), kTestValues['flutter.double']); - expect(sharedPreferences.getStringList('List'), kTestValues['flutter.List']); + expect( + sharedPreferences.getDouble('double'), kTestValues['flutter.double']); + expect( + sharedPreferences.getStringList('List'), kTestValues['flutter.List']); expect(log, equals([])); }); @@ -62,36 +64,41 @@ void main() { sharedPreferences.setInt('int', kTestValues2['flutter.int']); sharedPreferences.setDouble('double', kTestValues2['flutter.double']); sharedPreferences.setStringList('List', kTestValues2['flutter.List']); - expect(sharedPreferences.getString('String'), kTestValues2['flutter.String']); + expect(sharedPreferences.getString('String'), + kTestValues2['flutter.String']); expect(sharedPreferences.getBool('bool'), kTestValues2['flutter.bool']); expect(sharedPreferences.getInt('int'), kTestValues2['flutter.int']); - expect(sharedPreferences.getDouble('double'), kTestValues2['flutter.double']); - expect(sharedPreferences.getStringList('List'), kTestValues2['flutter.List']); + expect(sharedPreferences.getDouble('double'), + kTestValues2['flutter.double']); + expect(sharedPreferences.getStringList('List'), + kTestValues2['flutter.List']); expect(log, equals([])); await sharedPreferences.commit(); - expect(log, equals([ - new MethodCall( - 'setString', - { 'key': 'flutter.String', 'value': kTestValues2['flutter.String'] } - ), - new MethodCall( - 'setBool', - { 'key': 'flutter.bool', 'value': kTestValues2['flutter.bool'] } - ), - new MethodCall( - 'setInt', - { 'key': 'flutter.int', 'value': kTestValues2['flutter.int'] } - ), - new MethodCall( - 'setDouble', - { 'key': 'flutter.double', 'value': kTestValues2['flutter.double'] } - ), - new MethodCall( - 'setStringList', - { 'key': 'flutter.List', 'value': kTestValues2['flutter.List'] } - ), - const MethodCall('commit'), - ])); + expect( + log, + equals([ + new MethodCall('setString', { + 'key': 'flutter.String', + 'value': kTestValues2['flutter.String'] + }), + new MethodCall('setBool', { + 'key': 'flutter.bool', + 'value': kTestValues2['flutter.bool'] + }), + new MethodCall('setInt', { + 'key': 'flutter.int', + 'value': kTestValues2['flutter.int'] + }), + new MethodCall('setDouble', { + 'key': 'flutter.double', + 'value': kTestValues2['flutter.double'] + }), + new MethodCall('setStringList', { + 'key': 'flutter.List', + 'value': kTestValues2['flutter.List'] + }), + const MethodCall('commit'), + ])); }); test('clearing', () async { @@ -112,4 +119,4 @@ void main() { }); } -class MockPlatformChannel extends Mock implements MethodChannel { } +class MockPlatformChannel extends Mock implements MethodChannel {} diff --git a/packages/url_launcher/lib/url_launcher.dart b/packages/url_launcher/lib/url_launcher.dart index 088a0595629e..99086f23736c 100644 --- a/packages/url_launcher/lib/url_launcher.dart +++ b/packages/url_launcher/lib/url_launcher.dart @@ -6,7 +6,8 @@ import 'dart:async'; import 'package:flutter/services.dart'; -const MethodChannel _channel = const MethodChannel('plugins.flutter.io/url_launcher'); +const MethodChannel _channel = + const MethodChannel('plugins.flutter.io/url_launcher'); /// Parses the specified URL string and delegates handling of it to the /// underlying platform. @@ -24,8 +25,7 @@ Future launch(String urlString) { /// Checks whether the specified URL can be handled by some app installed on the /// device. Future canLaunch(String urlString) async { - if (urlString == null) - return false; + if (urlString == null) return false; return await _channel.invokeMethod( 'canLaunch', urlString, diff --git a/packages/url_launcher/test/url_launcher_test.dart b/packages/url_launcher/test/url_launcher_test.dart index 19ccd3bdd56f..e034c24439f1 100644 --- a/packages/url_launcher/test/url_launcher_test.dart +++ b/packages/url_launcher/test/url_launcher_test.dart @@ -7,7 +7,8 @@ import 'package:test/test.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { - const MethodChannel channel = const MethodChannel('plugins.flutter.io/url_launcher'); + const MethodChannel channel = + const MethodChannel('plugins.flutter.io/url_launcher'); final List log = []; channel.setMockMethodCallHandler((MethodCall methodCall) async { log.add(methodCall); @@ -21,14 +22,17 @@ void main() { await canLaunch('http://example.com/'); expect( log, - equals([const MethodCall('canLaunch', 'http://example.com/')]), + equals( + [const MethodCall('canLaunch', 'http://example.com/')]), ); log.clear(); }); test('launch test', () async { await launch('http://example.com/'); - expect(log, - equals([const MethodCall('launch', 'http://example.com/')])); + expect( + log, + equals( + [const MethodCall('launch', 'http://example.com/')])); }); }