diff --git a/packages/flutter_tools/templates/app/analysis_options.yaml.tmpl b/packages/flutter_tools/templates/app/analysis_options.yaml.tmpl new file mode 100644 index 0000000000..61b6c4de17 --- /dev/null +++ b/packages/flutter_tools/templates/app/analysis_options.yaml.tmpl @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/flutter_tools/templates/app/lib/main.dart.tmpl b/packages/flutter_tools/templates/app/lib/main.dart.tmpl index 225e9ca099..a18822bd1b 100644 --- a/packages/flutter_tools/templates/app/lib/main.dart.tmpl +++ b/packages/flutter_tools/templates/app/lib/main.dart.tmpl @@ -7,11 +7,13 @@ import 'package:{{pluginProjectName}}/{{pluginProjectName}}.dart'; {{/withPluginHook}} void main() { - runApp(MyApp()); + runApp(const MyApp()); } {{^withPluginHook}} class MyApp extends StatelessWidget { + const MyApp({Key? key}) : super(key: key); + // This widget is the root of your application. @override Widget build(BuildContext context) { @@ -29,13 +31,13 @@ class MyApp extends StatelessWidget { // is not restarted. primarySwatch: Colors.blue, ), - home: MyHomePage(title: 'Flutter Demo Home Page'), + home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { - MyHomePage({Key? key, required this.title}) : super(key: key); + const MyHomePage({Key? key, required this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect @@ -49,7 +51,7 @@ class MyHomePage extends StatefulWidget { final String title; @override - _MyHomePageState createState() => _MyHomePageState(); + State createState() => _MyHomePageState(); } class _MyHomePageState extends State { @@ -100,7 +102,7 @@ class _MyHomePageState extends State { // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( + const Text( 'You have pushed the button this many times:', ), Text( @@ -113,7 +115,7 @@ class _MyHomePageState extends State { floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', - child: Icon(Icons.add), + child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } @@ -121,8 +123,10 @@ class _MyHomePageState extends State { {{/withPluginHook}} {{#withPluginHook}} class MyApp extends StatefulWidget { + const MyApp({Key? key}) : super(key: key); + @override - _MyAppState createState() => _MyAppState(); + State createState() => _MyAppState(); } class _MyAppState extends State { diff --git a/packages/flutter_tools/templates/app/pubspec.yaml.tmpl b/packages/flutter_tools/templates/app/pubspec.yaml.tmpl index 2d6d9c464a..775addd147 100644 --- a/packages/flutter_tools/templates/app/pubspec.yaml.tmpl +++ b/packages/flutter_tools/templates/app/pubspec.yaml.tmpl @@ -2,7 +2,7 @@ name: {{projectName}} description: {{description}} # The following line prevents the package from being accidentally published to -# pub.dev using `pub publish`. This is preferred for private packages. +# pub.dev using `flutter pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev {{^withPluginHook}} @@ -22,6 +22,12 @@ version: 1.0.0+1 environment: sdk: {{dartSdkVersionBounds}} +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. dependencies: flutter: sdk: flutter @@ -44,6 +50,13 @@ dev_dependencies: flutter_test: sdk: flutter + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^1.0.0-0 + # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/packages/flutter_tools/templates/app/test/widget_test.dart.tmpl b/packages/flutter_tools/templates/app/test/widget_test.dart.tmpl index 6cd94fc776..fd5e4e4011 100644 --- a/packages/flutter_tools/templates/app/test/widget_test.dart.tmpl +++ b/packages/flutter_tools/templates/app/test/widget_test.dart.tmpl @@ -14,7 +14,7 @@ import 'package:{{projectName}}/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); + await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); @@ -34,7 +34,7 @@ void main() { void main() { testWidgets('Verify Platform version', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); + await tester.pumpWidget(const MyApp()); // Verify that platform version is retrieved. expect( diff --git a/packages/flutter_tools/templates/module/common/analysis_options.yaml.tmpl b/packages/flutter_tools/templates/module/common/analysis_options.yaml.tmpl new file mode 100644 index 0000000000..a5744c1cfb --- /dev/null +++ b/packages/flutter_tools/templates/module/common/analysis_options.yaml.tmpl @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/flutter_tools/templates/module/common/lib/main.dart.tmpl b/packages/flutter_tools/templates/module/common/lib/main.dart.tmpl index bba5115f44..d8ef114c40 100644 --- a/packages/flutter_tools/templates/module/common/lib/main.dart.tmpl +++ b/packages/flutter_tools/templates/module/common/lib/main.dart.tmpl @@ -6,10 +6,12 @@ import 'package:flutter/services.dart'; import 'package:{{pluginProjectName}}/{{pluginProjectName}}.dart'; {{/withPluginHook}} -void main() => runApp(MyApp()); +void main() => runApp(const MyApp()); {{^withPluginHook}} class MyApp extends StatelessWidget { + const MyApp({Key? key}) : super(key: key); + // This widget is the root of your application. @override Widget build(BuildContext context) { @@ -26,13 +28,13 @@ class MyApp extends StatelessWidget { // counter didn't reset back to zero; the application is not restarted. primarySwatch: Colors.blue, ), - home: MyHomePage(title: 'Flutter Demo Home Page'), + home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { - MyHomePage({Key? key, required this.title}) : super(key: key); + const MyHomePage({Key? key, required this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect @@ -46,7 +48,7 @@ class MyHomePage extends StatefulWidget { final String title; @override - _MyHomePageState createState() => _MyHomePageState(); + State createState() => _MyHomePageState(); } class _MyHomePageState extends State { @@ -97,7 +99,7 @@ class _MyHomePageState extends State { // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( + const Text( 'You have pushed the button this many times:', ), Text( @@ -110,7 +112,7 @@ class _MyHomePageState extends State { floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', - child: Icon(Icons.add), + child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } @@ -118,8 +120,10 @@ class _MyHomePageState extends State { {{/withPluginHook}} {{#withPluginHook}} class MyApp extends StatefulWidget { + const MyApp({Key? key}) : super(key: key); + @override - _MyAppState createState() => _MyAppState(); + State createState() => _MyAppState(); } class _MyAppState extends State { diff --git a/packages/flutter_tools/templates/module/common/pubspec.yaml.tmpl b/packages/flutter_tools/templates/module/common/pubspec.yaml.tmpl index 67da1d6dce..f4595c0791 100644 --- a/packages/flutter_tools/templates/module/common/pubspec.yaml.tmpl +++ b/packages/flutter_tools/templates/module/common/pubspec.yaml.tmpl @@ -31,6 +31,7 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + flutter_lints: ^1.0.0-0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/packages/flutter_tools/templates/module/common/test/widget_test.dart.tmpl b/packages/flutter_tools/templates/module/common/test/widget_test.dart.tmpl index 6cd94fc776..fd5e4e4011 100644 --- a/packages/flutter_tools/templates/module/common/test/widget_test.dart.tmpl +++ b/packages/flutter_tools/templates/module/common/test/widget_test.dart.tmpl @@ -14,7 +14,7 @@ import 'package:{{projectName}}/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); + await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); @@ -34,7 +34,7 @@ void main() { void main() { testWidgets('Verify Platform version', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); + await tester.pumpWidget(const MyApp()); // Verify that platform version is retrieved. expect( diff --git a/packages/flutter_tools/templates/package/analysis_options.yaml.tmpl b/packages/flutter_tools/templates/package/analysis_options.yaml.tmpl new file mode 100644 index 0000000000..a5744c1cfb --- /dev/null +++ b/packages/flutter_tools/templates/package/analysis_options.yaml.tmpl @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/flutter_tools/templates/package/pubspec.yaml.tmpl b/packages/flutter_tools/templates/package/pubspec.yaml.tmpl index 395990a010..55c7209e5f 100644 --- a/packages/flutter_tools/templates/package/pubspec.yaml.tmpl +++ b/packages/flutter_tools/templates/package/pubspec.yaml.tmpl @@ -14,6 +14,7 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + flutter_lints: ^1.0.0-0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/packages/flutter_tools/templates/plugin/analysis_options.yaml.tmpl b/packages/flutter_tools/templates/plugin/analysis_options.yaml.tmpl new file mode 100644 index 0000000000..a5744c1cfb --- /dev/null +++ b/packages/flutter_tools/templates/plugin/analysis_options.yaml.tmpl @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/flutter_tools/templates/plugin/lib/projectName.dart.tmpl b/packages/flutter_tools/templates/plugin/lib/projectName.dart.tmpl index f251211222..0e9ee9f4de 100644 --- a/packages/flutter_tools/templates/plugin/lib/projectName.dart.tmpl +++ b/packages/flutter_tools/templates/plugin/lib/projectName.dart.tmpl @@ -10,8 +10,7 @@ import 'dart:async'; import 'package:flutter/services.dart'; class {{pluginDartClass}} { - static const MethodChannel _channel = - const MethodChannel('{{projectName}}'); + static const MethodChannel _channel = MethodChannel('{{projectName}}'); static Future get platformVersion async { final String? version = await _channel.invokeMethod('getPlatformVersion'); diff --git a/packages/flutter_tools/templates/plugin/pubspec.yaml.tmpl b/packages/flutter_tools/templates/plugin/pubspec.yaml.tmpl index c45b539cbe..e391d0bdd5 100644 --- a/packages/flutter_tools/templates/plugin/pubspec.yaml.tmpl +++ b/packages/flutter_tools/templates/plugin/pubspec.yaml.tmpl @@ -18,6 +18,7 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + flutter_lints: ^1.0.0-0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/packages/flutter_tools/templates/template_manifest.json b/packages/flutter_tools/templates/template_manifest.json index 6ea0c93dbc..61cca6c21e 100644 --- a/packages/flutter_tools/templates/template_manifest.json +++ b/packages/flutter_tools/templates/template_manifest.json @@ -33,6 +33,7 @@ "templates/app/android.tmpl/gradle/wrapper/gradle-wrapper.properties", "templates/app/android.tmpl/gradle.properties.tmpl", "templates/app/android.tmpl/settings.gradle", + "templates/app/analysis_options.yaml.tmpl", "templates/app/ios-objc.tmpl/Runner/AppDelegate.h", "templates/app/ios-objc.tmpl/Runner/AppDelegate.m", "templates/app/ios-objc.tmpl/Runner/main.m", @@ -170,6 +171,7 @@ "templates/module/common/.idea/modules.xml.tmpl", "templates/module/common/.idea/workspace.xml.tmpl", "templates/module/common/.metadata.tmpl", + "templates/module/common/analysis_options.yaml.tmpl", "templates/module/common/lib/main.dart.tmpl", "templates/module/common/projectName.iml.tmpl", "templates/module/common/projectName_android.iml.tmpl", @@ -229,6 +231,7 @@ "templates/package/.idea/modules.xml.tmpl", "templates/package/.idea/workspace.xml.tmpl", "templates/package/.metadata.tmpl", + "templates/package/analysis_options.yaml.tmpl", "templates/package/CHANGELOG.md.tmpl", "templates/package/lib/projectName.dart.tmpl", "templates/package/LICENSE.tmpl", @@ -242,6 +245,7 @@ "templates/plugin/.idea/runConfigurations/example_lib_main_dart.xml.tmpl", "templates/plugin/.idea/workspace.xml.tmpl", "templates/plugin/.metadata.tmpl", + "templates/plugin/analysis_options.yaml.tmpl", "templates/plugin/android-java.tmpl/build.gradle.tmpl", "templates/plugin/android-java.tmpl/projectName_android.iml.tmpl", "templates/plugin/android-java.tmpl/src/main/java/androidIdentifier/pluginClass.java.tmpl", diff --git a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart index 8de421147d..78a9f8d1cc 100755 --- a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart @@ -90,6 +90,7 @@ void main() { projectDir, ['-i', 'objc', '-a', 'java'], [ + 'analysis_options.yaml', 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', @@ -117,6 +118,7 @@ void main() { projectDir, ['-i', 'objc', '-a', 'java'], [ + 'analysis_options.yaml', 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', @@ -146,6 +148,7 @@ void main() { '.ios/Flutter/flutter_project.podspec', '.ios/Flutter/engine/Flutter.podspec', '.metadata', + 'analysis_options.yaml', 'lib/main.dart', 'pubspec.yaml', 'README.md', @@ -380,6 +383,7 @@ void main() { projectDir, ['--template=package'], [ + 'analysis_options.yaml', 'lib/flutter_project.dart', 'test/flutter_project_test.dart', ], @@ -417,6 +421,7 @@ void main() { projectDir, ['--template=plugin', '-i', 'objc', '-a', 'java'], [ + 'analysis_options.yaml', 'example/lib/main.dart', 'flutter_project.iml', 'lib/flutter_project.dart', @@ -500,6 +505,7 @@ void main() { projectDir, ['--no-pub', '--template=plugin', '-a', 'kotlin', '--ios-language', 'swift', '--platforms', 'ios,android'], [ + 'analysis_options.yaml', 'android/src/main/kotlin/com/example/flutter_project/FlutterProjectPlugin.kt', 'example/android/app/src/main/kotlin/com/example/flutter_project_example/MainActivity.kt', 'example/ios/Runner/AppDelegate.swift', @@ -592,6 +598,7 @@ void main() { '.gitignore', '.metadata', '.packages', + 'analysis_options.yaml', 'lib/main.dart', 'pubspec.lock', 'pubspec.yaml', @@ -1691,7 +1698,7 @@ void main() { return FakeHttpClient.list([ FakeRequest( Uri.parse('https://master-api.flutter.dev/snippets/foo.bar.Baz.dart'), - response: FakeResponse(body: utf8.encode('void main() { String? foo; print(foo); }')), + response: FakeResponse(body: utf8.encode('void main() { String? foo; print(foo); } // ignore: avoid_print')), ) ]); }; @@ -2450,6 +2457,47 @@ void main() { FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true, isAndroidEnabled: false, isIOSEnabled: false), Logger: () => logger, }); + + testUsingContext('default project has analysis_options.yaml set up correctly', () async { + await _createProject( + projectDir, + [], + [ + 'analysis_options.yaml', + ], + ); + final String dataPath = globals.fs.path.join( + getFlutterRoot(), + 'packages', + 'flutter_tools', + 'test', + 'commands.shard', + 'permeable', + 'data', + ); + final File toAnalyze = await globals.fs.file(globals.fs.path.join(dataPath, 'to_analyze.dart.test')) + .copy(globals.fs.path.join(projectDir.path, 'lib', 'to_analyze.dart')); + final String relativePath = globals.fs.path.join('lib', 'to_analyze.dart'); + final List expectedFailures = [ + '$relativePath:11:7: use_key_in_widget_constructors', + '$relativePath:20:3: prefer_const_constructors_in_immutables', + '$relativePath:31:26: use_full_hex_values_for_flutter_colors', + ]; + expect(expectedFailures.length, '// LINT:'.allMatches(toAnalyze.readAsStringSync()).length); + await _analyzeProject( + projectDir.path, + expectedFailures: expectedFailures, + ); + }, overrides: { + Pub: () => Pub( + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + usage: globals.flutterUsage, + botDetector: globals.botDetector, + platform: globals.platform, + ), + }); } Future _createProject( @@ -2548,7 +2596,7 @@ Future _restoreFlutterToolsSnapshot() async { snapshotBackup.renameSync(flutterToolsSnapshotPath); } -Future _analyzeProject(String workingDir) async { +Future _analyzeProject(String workingDir, { List expectedFailures = const [] }) async { final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( '..', '..', @@ -2567,11 +2615,27 @@ Future _analyzeProject(String workingDir) async { args, workingDirectory: workingDir, ); - if (exec.exitCode != 0) { - print(exec.stdout); - print(exec.stderr); + if (expectedFailures.isEmpty) { + if (exec.exitCode != 0) { + print(exec.stdout); + print(exec.stderr); + } + expect(exec.exitCode, 0); + return; } - expect(exec.exitCode, 0); + expect(exec.exitCode, isNot(0)); + String lineParser(String line) { + print('#$line#'); + final String analyzerSeparator = globals.platform.isWindows ? ' - ' : ' • '; + final List lineComponents = line.trim().split(analyzerSeparator); + final String lintName = lineComponents.removeLast(); + final String location = lineComponents.removeLast(); + return '$location: $lintName'; + } + final List errors = const LineSplitter().convert(exec.stdout.toString()) + .where((String line) => line.trim().isNotEmpty && !line.startsWith('Analyzing')) + .map(lineParser).toList(); + expect(errors, unorderedEquals(expectedFailures)); } Future _runFlutterTest(Directory workingDir, { String target }) async { diff --git a/packages/flutter_tools/test/commands.shard/permeable/data/to_analyze.dart.test b/packages/flutter_tools/test/commands.shard/permeable/data/to_analyze.dart.test new file mode 100644 index 0000000000..1bec7f929e --- /dev/null +++ b/packages/flutter_tools/test/commands.shard/permeable/data/to_analyze.dart.test @@ -0,0 +1,59 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/widgets.dart'; + +// Test file used by `create_test.dart` to verify that `flutter create` sets up +// `analysis_options.yaml` correctly to activate certain lints and ensures +// that lints not playing well with Flutter remain disabled. + +class NoConstructor extends StatelessWidget { + // LINT: Missing constructor generates use_key_in_widget_constructors warning. + + @override + Widget build(BuildContext context) => Container(); +} + +class NoConstConstructor extends StatelessWidget { + // LINT: Missing const constructor generates prefer_const_constructors_in_immutables warning. + NoConstConstructor({Key? key, required this.name }) : super(key: key); + + final String name; + + @override + Widget build(BuildContext context) { + // NO LINT: Can type local variables without omit_local_variable_types warning. + final String text = 'Hello $name'; + + return Container( + // LINT: "Color(0x1)" generates use_full_hex_values_for_flutter_colors warning. + color: const Color(0x1), + child: Text(text), + ); + } +} + +Future playAsync(AnimationController controller) async { + // NO LINT: AnimationController API can be called without await and without + // marking Future as unawaited, https://github.com/dart-lang/linter/issues/2513. + controller.forward(); +} + +Future pushAsync(NavigatorState navigator) async { + // NO LINT: Navigator API can be called without await and without + // marking Future as unawaited, https://github.com/dart-lang/linter/issues/2513. + navigator.pushNamed('foo'); +} + +// NO LINT: Can extend ChangeNotifier without warning, https://github.com/dart-lang/sdk/issues/45343. +class ExtendingChangeNotifier extends ChangeNotifier { } + +// NO LINT: Can mixin ChangeNotifier without warning, https://github.com/dart-lang/sdk/issues/45343. +class MixingChangeNotifier with ChangeNotifier { } + +// NO LINT: Can extend WidgetsBindingObserver without warning, https://github.com/dart-lang/sdk/issues/45343. +class ExtendingWidgetsBindingObserver extends WidgetsBindingObserver { } + +// NO LINT: Can mixin WidgetsBindingObserver without warning, https://github.com/dart-lang/sdk/issues/45343. +class MixingWidgetsBindingObserver with WidgetsBindingObserver { }