Unverified Commit 532a79c8 authored by Michael Goderbauer's avatar Michael Goderbauer Committed by GitHub

Integrate package:flutter_lints into templates (#81417)

parent 1d8ab0f0
# 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
......@@ -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<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
......@@ -100,7 +102,7 @@ class _MyHomePageState extends State<MyHomePage> {
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
const Text(
'You have pushed the button this many times:',
),
Text(
......@@ -113,7 +115,7 @@ class _MyHomePageState extends State<MyHomePage> {
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<MyHomePage> {
{{/withPluginHook}}
{{#withPluginHook}}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
......
......@@ -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
......
......@@ -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(
......
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
......@@ -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<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
......@@ -97,7 +99,7 @@ class _MyHomePageState extends State<MyHomePage> {
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
const Text(
'You have pushed the button this many times:',
),
Text(
......@@ -110,7 +112,7 @@ class _MyHomePageState extends State<MyHomePage> {
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<MyHomePage> {
{{/withPluginHook}}
{{#withPluginHook}}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
......
......@@ -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
......
......@@ -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(
......
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
......@@ -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
......
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
......@@ -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<String?> get platformVersion async {
final String? version = await _channel.invokeMethod('getPlatformVersion');
......
......@@ -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
......
......@@ -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",
......
......@@ -90,6 +90,7 @@ void main() {
projectDir,
<String>['-i', 'objc', '-a', 'java'],
<String>[
'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,
<String>['-i', 'objc', '-a', 'java'],
<String>[
'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,
<String>['--template=package'],
<String>[
'analysis_options.yaml',
'lib/flutter_project.dart',
'test/flutter_project_test.dart',
],
......@@ -417,6 +421,7 @@ void main() {
projectDir,
<String>['--template=plugin', '-i', 'objc', '-a', 'java'],
<String>[
'analysis_options.yaml',
'example/lib/main.dart',
'flutter_project.iml',
'lib/flutter_project.dart',
......@@ -500,6 +505,7 @@ void main() {
projectDir,
<String>['--no-pub', '--template=plugin', '-a', 'kotlin', '--ios-language', 'swift', '--platforms', 'ios,android'],
<String>[
'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>[
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,
<String>[],
<String>[
'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<String> expectedFailures = <String>[
'$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: <Type, Generator>{
Pub: () => Pub(
fileSystem: globals.fs,
logger: globals.logger,
processManager: globals.processManager,
usage: globals.flutterUsage,
botDetector: globals.botDetector,
platform: globals.platform,
),
});
}
Future<void> _createProject(
......@@ -2548,7 +2596,7 @@ Future<void> _restoreFlutterToolsSnapshot() async {
snapshotBackup.renameSync(flutterToolsSnapshotPath);
}
Future<void> _analyzeProject(String workingDir) async {
Future<void> _analyzeProject(String workingDir, { List<String> expectedFailures = const <String>[] }) async {
final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join(
'..',
'..',
......@@ -2567,11 +2615,27 @@ Future<void> _analyzeProject(String workingDir) async {
args,
workingDirectory: workingDir,
);
if (expectedFailures.isEmpty) {
if (exec.exitCode != 0) {
print(exec.stdout);
print(exec.stderr);
}
expect(exec.exitCode, 0);
return;
}
expect(exec.exitCode, isNot(0));
String lineParser(String line) {
print('#$line#');
final String analyzerSeparator = globals.platform.isWindows ? ' - ' : ' • ';
final List<String> lineComponents = line.trim().split(analyzerSeparator);
final String lintName = lineComponents.removeLast();
final String location = lineComponents.removeLast();
return '$location: $lintName';
}
final List<String> errors = const LineSplitter().convert(exec.stdout.toString())
.where((String line) => line.trim().isNotEmpty && !line.startsWith('Analyzing'))
.map(lineParser).toList();
expect(errors, unorderedEquals(expectedFailures));
}
Future<void> _runFlutterTest(Directory workingDir, { String target }) async {
......
// 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<void> 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<void> 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 { }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment