介紹 package:flutter_lints
概述
#package:flutter_lints 定義了最新的推薦 lint 集合,鼓勵 Flutter 應用、包和外掛遵循良好的編碼實踐。使用 Flutter 2.5 或更新版本透過 flutter create 建立的專案已啟用最新的推薦 lint 集合。早於該版本的專案可以透過本指南中的說明進行升級。
背景
#在引入 package:flutter_lints 之前,Flutter 框架自帶了一組在 analysis_options_user.yaml 中定義的 lint,如果 Flutter 專案沒有定義自定義 analysis_options.yaml 檔案,則由 dart analyzer 使用它來識別程式碼問題。由於 analysis_options_user.yaml 與特定框架版本繫結,因此很難在不破壞現有應用、包和外掛的情況下進行演進。因此,analysis_options_user.yaml 中定義的 lint 已嚴重過時。為了解決這個問題,建立了 package:flutter_lints。該包對 lint 集合進行版本控制,使其能夠在不破壞現有專案的情況下進行演進。由於該包建立在 Dart 的 package:lints 之上,因此也使推薦給 Flutter 專案的 lint 與 Dart 生態系統的其餘部分保持一致。
遷移指南
#請按照以下步驟將您的 Flutter 專案遷移到使用 package:flutter_lints 的最新推薦 lint。
透過在專案根目錄下執行 flutter pub add --dev flutter_lints,將 package:flutter_lints 新增到您專案的 pubspec.yaml 檔案中作為開發依賴項。
在專案根目錄下(與 pubspec.yaml 檔案相鄰)建立一個 analysis_options.yaml 檔案,內容如下:
include: package:flutter_lints/flutter.yaml新啟用的 lint 集合可能會在您的程式碼中識別出一些新問題。要找到它們,請在支援 Dart 的 IDE 中開啟您的專案,或在命令列中執行 flutter analyze。您可以透過在專案根目錄下執行 dart fix --apply 來自動修復其中一些報告的問題。
現有的自定義 analysis_options.yaml 檔案
#如果您的專案根目錄下已有一個自定義的 analysis_options.yaml 檔案,請在檔案頂部新增 include: package:flutter_lints/flutter.yaml 來啟用 package:flutter_lints 的 lint。如果您的 analysis_options.yaml 已包含 include: 指令,您必須決定是保留那些 lint 還是用 package:flutter_lints 的 lint 替換它們,因為 Dart analyzer 每個 analysis_options.yaml 檔案只支援一個 include: 指令。
自定義 lint
#給定專案啟用的 lint 可以在 analysis_options.yaml 檔案中進一步自定義。以下示例檔案展示了這一點,該檔案是 flutter create 為新專案生成的 analysis_options.yaml 檔案的重現。
# 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.lang.tw/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.lang.tw/guides/language/analysis-options時間線
#釋出於版本:2.3.0-12.0.pre
穩定版本:2.5
參考資料
#文件
相關議題
相關 PR