iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚔

Flutter templates now include a linter

に公開
2023/05/07
1件

Update (2021/9/10)

Flutter 2.5.0 has successfully reached Stable, and flutter_lints has arrived in Stable! 🙌

https://medium.com/flutter/whats-new-in-flutter-2-5-6f080c3f3dc

Main Part

Hello and good evening, I'm Sugitto ٩( ᐛ )و.
Today's theme is Linter.

The other day, while I was surfing Flutter issues (a mysterious hobby of mine), I found this.

https://github.com/flutter/flutter/issues/78432

And then this PR.

https://github.com/flutter/flutter/pull/81417

Just as I was thinking an announcement might be coming soon...

https://flutter.dev/docs/release/breaking-changes/flutter-lints-package

It arrived! ٩( ᐛ )و

I'll touch on the details later, but first, I'll provide just the conclusion.

What happened as a result of this is:

Linter is now included by default in the Flutter app template created with "flutter create my_app"

The official Flutter team has changed the template. This is a big deal!
Let's take a look at what has changed.

What is a Linter?

It's the source code police 👮🏻‍♂️.

If you're familiar with frameworks and languages other than Flutter or Dart, many of you likely use Linters in those areas. Here, I'll give a brief explanation for those who are new to Linters.

First, the role of a Linter is what's called static analysis. Here, static refers to analyzing source code at the stage before the app is executed to provide necessary information. Automated testing is also sometimes called static analysis, so I think static analysis is a fairly broad term. A general definition would be: "Analyzing and finding problems (or potential problems) in a program without executing the executable program itself." Please Google it for a more precise definition.

In other words, a Linter is a type of static analysis tool that analyzes source code without building the Flutter app and points out parts that do not follow certain rules. In that sense, it's often called the "police" of app development. (Is it just me...?)

Now, I mentioned it briefly, but the "parts that do not follow certain rules" is the key point.

Usually, Linter refers to the program itself that analyzes source code according to rules. Therefore, the role of the app developer using the Linter is to provide "rules" to the Linter static analysis program. So, how do we provide rules in Flutter? And what exactly are these rules in the first place?

In this article, while weaving in those explanations, I'll talk about the rules that have been newly added to the Flutter template.

Why is a Linter Necessary?

Depending on the characteristics of each programming language, source code is relatively flexible in achieving its purpose. Therefore, in any language, there are best practices and official recommended/deprecated ways of writing. I believe programmers are creatures who constantly update their knowledge to find better ways of writing.

Now, let's say a group of programmers belonging to an organization is building an app.

In a reasonably mature organization, they likely have coding conventions—a set of local rules—maintained as documents. Typically, when someone newly joins the organization and is assigned to a project, they are expected to read those conventions and implement accordingly. That's what it means to belong to a group.
While that was fine in the past, lately, having humans read a document and follow conventions is said to be a high burden for both the implementer and the reviewer. Oversight happens frequently, causing the source code to become messy, and eventually, these oversights can significantly degrade performance.

Programmers are creatures who put all their effort into finding ways to be lazy (efficient). A Linter is exactly that. By defining coding conventions in a format that a program can interpret, it makes it possible to constantly monitor the source code. As a result, neither implementers nor reviewers need to worry about checking whether the conventions are followed.

Following these rules has the benefit of guaranteeing a certain level of quality, in addition to simply making the source code look consistent. This is a very significant advantage.

For example, in Flutter, there is a rule:

"Add const to Widgets that are not expected to change."

There's a rule like this (see below).
https://dart-lang.github.io/linter/lints/prefer_const_constructors.html

This exists because the cost of creating the RenderObject corresponding to a Widget is not negligible. If the Widget's definition doesn't change, it's better for performance to keep and reuse it. This is often cited as one of the first things to do for Flutter performance optimization.

By setting such things as rules and running a Linter program, even if an implementer forgets to add const, the Linter will remind them, saying, "Hey, add const!"

It looks like this.

Did Flutter have a Linter before?

Of course, it did.

  • pedantic
  • effective_dart

These were famous, but both have become deprecated.

https://pub.dev/packages/pedantic

https://pub.dev/packages/effective_dart

Why did they become deprecated?

First, the readme for pedantic stated:

This package is deprecated.

Before it was deprecated, it was the way to get analysis options matching those used internally at Google. This was useful because it was a good starting point for which lints to enable.
Instead, please see package:lints which is the lint recommendation from the Dart team, or package:flutter_lints which extends that for Flutter. These are better than the Google lint set because they take into account the needs of all Dart users, not just Google engineers.

Also, effective_dart had this description:

This package is deprecated.

Before it was deprecated, it was the way to provide analysis options corresponding to the guidelines in Effective Dart.
Instead, please see official packages: package:lints which is the lint recommendation from the Dart team, or package:flutter_lints which extends that for Flutter.

Both packages are essentially saying, "Flutter has officially provided recommended rules, so please use those instead."

I was also a big fan of pedantic, but with a feeling of gratitude, I moved over to the new package.

How do you set up a Linter?

Just write an analysis_options.yaml file.
I posted the link at the beginning of this article, but I'll share it again.

https://flutter.dev/docs/release/breaking-changes/flutter-lints-package

Everything is explained there, so I'll just provide an overview.

  • Add flutter_lints: ^1.0.0 (Please check the package version as needed).
  • Place analysis_options.yaml at the top of your Flutter project (the same level as pubspec.yaml).

That's it.

For reference, here is the analysis_options.yaml file introduced in Flutter 2.3.0 - 12.0pre:

https://github.com/flutter/flutter/blob/2.3.0-12.0.pre/packages/flutter_tools/templates/app/analysis_options.yaml.tmpl

What rules are in flutter_lints?

flutter_lints defines the rule set officially recommended by Flutter. The analysis_options.yaml template mentioned earlier imports the recommended rule set from the flutter_lints package. It's this part: include: package:flutter_lints/flutter.yaml.

If you want to add more rules, you can append them to analysis_options.yaml to operate with:

Recommended rules from flutter_lints + Your own custom rules

This means it's probably good to know what is included in the recommended rule set proposed by flutter_lints.

...

Having said that, there are an enormous number of them.

Honestly, rather than checking every single rule, I think a stance of "fix it when you get warned" is perfectly fine.

Let's take a quick look anyway.

flutter_lints

https://github.com/flutter/packages/blob/master/packages/flutter_lints/lib/flutter.yaml

It's exactly as shown here.
Oh, look, it says include: package:lints/recommended.yaml. This means it's importing rules from lints/recommended.yaml.

lints/recommended

https://github.com/dart-lang/lints/blob/main/lib/recommended.yaml

That's quite a lot... ( ᐛ )

And it includes package:lints/core.yaml.

lints/core

https://github.com/dart-lang/lints/blob/main/lib/core.yaml

Finally reached the end.

Rule Definitions

If you want to know the meaning of each rule, you can refer to the page below. Also, if you want to add rules independently, you can select them from the following Dart lints.

"I got warned by the Linter, but I don't know how to fix it!"

In such cases, if you search for the keyword from the error message on the following page, you'll find "Good" and "Bad" code examples, which should help you understand.

https://dart-lang.github.io/linter/lints/index.html

For example, regarding the const case mentioned earlier:

prefer_const_constructors is the name of the rule. Please try searching for that.

Addendum: To Avoid Misunderstanding

mono's pedantic_mono has been updated to be based on flutter_lints. That was quick...

https://pub.dev/packages/pedantic_mono

In that context, they mentioned the following:

https://twitter.com/_mono/status/1412534254093758464?s=20

I'm adding this because I didn't want my article to lead to this kind of misunderstanding.
If you read carefully, I think it's clear that flutter_lints simply became the default and that you can add your own rules to analysis_options.yaml. However, if you just skim through it, I'm afraid it might be perceived as a story about package selection, like:

I see... 🤤
So pedantic and effective_dart are deprecated... 🤤
From now on, it's flutter_lints... 🤤

What Matters is the "Rule Set"

You should choose which package to use based on the rule set you want to adopt.
Think of flutter_lints as something that has emerged as a baseline.

  • To those who haven't introduced a Linter yet:
    • Why not start with flutter_lints? It's time to graduate from not using a Linter.
  • To those who have been using a Linter:
    • Compare the rules in flutter_lints with the rules you are currently using. Then, add more rules as needed.
  • To those who want to master the Linter even more:
    • There are several packages that provide collections of Linter rules. Use them as a reference and actively adopt rules that can be implemented in your project. Additionally, some packages you use may have their own recommended rules. You might want to refer to those as well.

Reference

Rule set enabled by flutter_lints alone

  • always_require_non_null_named_parameters
  • annotate_overrides
  • avoid_empty_else
  • avoid_function_literals_in_foreach_calls
  • avoid_init_to_null
  • avoid_null_checks_in_equality_operators
  • avoid_print
  • avoid_relative_lib_imports
  • avoid_renaming_method_parameters
  • avoid_return_types_on_setters
  • avoid_returning_null_for_void
  • avoid_shadowing_type_parameters
  • avoid_single_cascade_in_expression_statements
  • avoid_types_as_parameter_names
  • avoid_unnecessary_containers
  • avoid_web_libraries_in_flutter
  • await_only_futures
  • camel_case_extensions
  • camel_case_types
  • constant_identifier_names
  • control_flow_in_finally
  • curly_braces_in_flow_control_structures
  • empty_catches
  • empty_constructor_bodies
  • empty_statements
  • exhaustive_cases
  • file_names
  • hash_and_equals
  • implementation_imports
  • iterable_contains_unrelated_type
  • library_names
  • library_prefixes
  • list_remove_unrelated_type
  • no_duplicate_case_values
  • no_logic_in_create_state
  • non_constant_identifier_names
  • null_closures
  • overridden_fields
  • package_names
  • package_prefixed_library_names
  • prefer_adjacent_string_concatenation
  • prefer_collection_literals
  • prefer_conditional_assignment
  • prefer_const_constructors
  • prefer_const_constructors_in_immutables
  • prefer_const_declarations
  • prefer_const_literals_to_create_immutables
  • prefer_contains
  • prefer_equal_for_default_values
  • prefer_final_fields
  • prefer_for_elements_to_map_fromIterable
  • prefer_function_declarations_over_variables
  • prefer_generic_function_type_aliases
  • prefer_if_null_operators
  • prefer_initializing_formals
  • prefer_inlined_adds
  • prefer_is_empty
  • prefer_is_not_empty
  • prefer_is_not_operator
  • prefer_iterable_whereType
  • prefer_null_aware_operators
  • prefer_spread_collections
  • prefer_typing_uninitialized_variables
  • prefer_void_to_null
  • provide_deprecation_message
  • recursive_getters
  • sized_box_for_whitespace
  • slash_for_doc_comments
  • type_init_formals
  • unnecessary_brace_in_string_interps
  • unnecessary_const
  • unnecessary_getters_setters
  • unnecessary_new
  • unnecessary_null_in_if_null_operators
  • unnecessary_overrides
  • unnecessary_string_escapes
  • unnecessary_string_interpolations
  • unnecessary_this
  • unrelated_type_equality_checks
  • use_full_hex_values_for_flutter_colors
  • use_function_type_syntax_for_parameters
  • use_key_in_widget_constructors
  • use_rethrow_when_possible
  • valid_regexps
  • void_checks

Rule set added in pedantic_mono

In pedantic_mono, the following rules are adopted in addition to the flutter_lints rules.

  • always_declare_return_types
  • always_put_control_body_on_new_line
  • avoid_bool_literals_in_conditional_expressions
  • avoid_catches_without_on_clauses
  • avoid_catching_errors
  • avoid_classes_with_only_static_members
  • avoid_double_and_int_checks
  • avoid_dynamic_calls
  • avoid_field_initializers_in_const_classes
  • avoid_implementing_value_types
  • avoid_js_rounded_ints
  • avoid_multiple_declarations_per_line
  • avoid_positional_boolean_parameters
  • avoid_private_typedef_functions
  • avoid_returning_null
  • avoid_returning_this
  • avoid_setters_without_getters
  • avoid_slow_async_io
  • avoid_type_to_string
  • avoid_unused_constructor_parameters
  • avoid_void_async
  • cancel_subscriptions
  • cascade_invocations
  • cast_nullable_to_non_nullable
  • close_sinks
  • comment_references
  • deprecated_consistency
  • directives_ordering
  • flutter_style_todos
  • invariant_booleans
  • join_return_with_assignment
  • lines_longer_than_80_chars
  • literal_only_boolean_expressions
  • no_adjacent_strings_in_list
  • no_default_cases
  • null_check_on_nullable_type_parameter
  • omit_local_variable_types
  • one_member_abstracts
  • only_throw_errors
  • package_api_docs
  • parameter_assignments
  • prefer_asserts_in_initializer_lists
  • prefer_constructors_over_static_methods
  • prefer_final_in_for_each
  • prefer_final_locals
  • prefer_foreach
  • prefer_int_literals
  • prefer_interpolation_to_compose_strings
  • prefer_single_quotes
  • sort_child_properties_last
  • sort_constructors_first
  • sort_pub_dependencies
  • sort_unnamed_constructors_first
  • test_types_in_equals
  • throw_in_finally
  • tighten_type_of_initializing_formals
  • type_annotate_public_apis
  • unawaited_futures
  • unnecessary_await_in_return
  • unnecessary_lambdas
  • unnecessary_null_aware_assignments
  • unnecessary_null_checks
  • unnecessary_nullable_for_final_variable_declarations
  • unnecessary_parenthesis
  • unnecessary_statements
  • unsafe_html
  • use_is_even_rather_than_modulo
  • use_late_for_private_fields_and_variables
  • use_named_constants
  • use_setters_to_change_properties
  • use_string_buffers
  • use_to_and_as_if_applicable

Summary

Linters bring order to code. Order brings peace of mind and trust to the source code. It also allows you to clear the minimum bar in terms of performance. If you haven't used a Linter before, I highly recommend considering its introduction.

By the way, the Linter is introduced via "flutter create my_app" in version 2.3.0-12.0.pre and later.

https://github.com/flutter/flutter/releases/tag/2.3.0-12.0.pre

At the time of writing this article, the Stable version is still 2.2.3, so you can try it out by switching channels.

Until then, you'll have to introduce it manually, but why not start by following the template changes that will be coming to Stable in the near future?

That's all for now.

Sugitto ٩( ᐛ )و

GitHubで編集を提案

Discussion

まつまるまつまる

すごく参考になりました!ありがとうございます!