yii.
← Writing
Flutter 技術 · · 17 min read

Flutter 3.24 和 Dart 3.5 重點回顧!

熱騰騰的改版好消息來了

Announcing Flutter 3.24 and Dart 3.5An early look at Flutter GPU, web enhancements, and more!medium.com

What’s new in Flutter 3.24Unleashing Flutter GPU, Multi-View Embedding, and Moremedium.com

Announcing Dart 3.5, and an update on the Dart roadmapIt’s time for another of our quarterly Dart SDK releases. We have improvements in interoperability, new features in our…medium.com

Getting started with Flutter GPUBuild custom renderers and render 3D scenes in Flutter.medium.com

Flutter 3.24.0 release notesRelease notes for Flutter 3.24.0.docs.flutter.dev


sdk/CHANGELOG.md at main · dart-lang/sdkThe Dart SDK, including the VM, dart2js, core libraries, and more. - sdk/CHANGELOG.md at main · dart-lang/sdkgithub.com

Web Interoperability#

Web 編譯到 WebAssembly 需要使用新的 JS interoperability API,現在是穩定版本,並且已將 package:web(要替換舊的dart:html庫)中的瀏覽器 API 升級到版本 1.0。

Migrate to package:webHow to migrate web interop code from dart:html to package:web.dart.dev

官方鼓勵所有 Web 套件作者遷移到 package:web,並計劃在下一個 Dart 版本中棄用舊的互通 API(dart:html、dart:js、package:js 等),並在明年棄用它們。

使用後如有任何問題,可以到 issue 中提供回饋:

@depreacte dart:html and other “legacy” DOM libraries · Issue #56358 · dart-lang/sdkWe’d like to fully remove these in 2025. Having them deprecated with a year lead time is a good idea. dart:html…github.com

Mobile Interoperability#

C#

支援將指標從 Dart TypedData 物件直接傳遞到 FFI,避免將記憶體從 Dart 複製到 Native 的成本。

[vm/ffi] Implement TypedData unwrapping to Pointers in Leaf calls · Issue #44589 · dart-lang/sdkAfter implementing leaf calls (#36707), we should support passing typed data into FFI trampolines. Leaf calls will not…github.com

Java & Kotlin#

啟用 JNIgen generator,自動生成綁定程式碼,以便 Dart 透過 Java Native Iterface ( JNI ) 呼叫到 Java 和 Kotlin。停止了以前的 C-based bindings,現在具有更好的性能,並且更易於使用。

目前處於 preview 版本,預計將在兩個季度內完成穩定版本 1.0

jnigen | Dart packageA Dart bindings generator for Java and Kotlin that uses JNI under the hood to interop with Java virtual machine.pub.dev

Deprecate C based bindings and default to pure dart bindings · Issue #660 · dart-lang/nativeI believe pure dart bindings are the future. If there’s a significant disrepancy in performance between C based and…github.com

JNIgen tracker * dart-langTracker for JNIgen: a Dart bindings generator for Java and Kotlin that uses JNI under the hood to interop with Java…github.com

Objective-C#

建構在 FFI 和 FFIgen 生成器之上。新增了對 Objective-C 協定和常見類型,例如:NSString。

目前處於 preview 版本,明年將專注在支援 Swift 互通性的部分

Objective-C and Swift interop using package:ffigenTo use Objective-C and Swift code in your Dart program, use package:ffigen.dart.dev

http/pkgs/cupertino_http at master · dart-lang/httpA composable API for making HTTP requests in Dart. - http/pkgs/cupertino_http at master · dart-lang/httpgithub.com

ObjC/Swift interop * dart-langGitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to…github.com

Pub.dev Package#

topic 設置#

針對套件的 topic 設置上做了優化,可以指定主題的別名,新增 aliases topic,可涵蓋相似的關鍵字。

topics:
- topic: widget
  description: Packages that contain Flutter widgets.
  aliases:
  - widgets
- topic: logging
  description: Packages for writing log messages.
  aliases:
  - logger
  - logs
  - log
- topic: testing
  description: Packages that facilitate testing
  aliases:
  - test

pub-dev/doc/topics.yaml at master · dart-lang/pub-devThe pub.dev website. Contribute to dart-lang/pub-dev development by creating an account on GitHub.github.com

下載套件專案#

新增了一個新 pub unpack 指令。可以將套件下載到本地的方法,進而在本地存取它們。

dart pub unpack <package-name>

例如,如果想在本機上執行套件的 exmaple/,則可以使用此方法:

$ dart pub unpack path
$ cd path-1.9.0/example/
$ dart run example.dart

檢查版本約束#

新的 pub downgrade 指令用於檢查套件依賴約束。運行後,它會將較低的約束更新為 pub 能夠解決問題的最低版本。

dart pub downgrade --tighten

套件的下載數指標#

有關每個套件的使用與下載數量指標,取得了良好進展,希望在年底前推出預覽版本。

Improved metrics: Measure and report the download count · Issue #2714 · dart-lang/pub-devAs a developer and owner of a package, I would like to see the download stats for my package. The npm package…github.com


其中包括幾項更新與優化:

  1. Flutter GPU 早期預覽
  2. Element Embedding for Web 強化
  3. Swift Package Manager 早期預覽
  4. Cupertino 元件更新

Flutter Framework#

What’s new in Flutter 3.24Unleashing Flutter GPU, Multi-View Embedding, and Moremedium.com

Flutter Engine#

主要 Impeller 提高性能和保真度

✔️極大地提高了表情符號滾動的性能,消除滾動大量表情符號時的卡頓。

[Impeller] Poor performance with lots of emojis. · Issue #138798 · flutter/flutterSteps to reproduce see #134292 The only difference is that the emojis get displayed, which fixed that task, but they…github.com

✔️對於文字粗細、間距和字距調整,現在都與舊版 Skia 渲染器的文字保真度相同。

[Impeller] Use scaled font to determine bounds, match Skia position rounding behavior, add subpixel…Multiple fixes to text rendering that match skia behavior on almost all bugs I&#39;ve found, except for the glyphs are…github.com

Before and After
Before and After

Impeller Improvement and Flutter GPU for 3D#

Flutter 在 Impeller 和 Shader 方面取得了進展,解鎖了圖形領域的新可能性,例如:3D。

✔️Flutter GPU

全新的低階圖形 API,稱為 Flutter GPU,是一個直接整合到 Flutter SDK 中的低階圖形 API。允許開發人員使用 Dart 和 GLSL 著色器建立 raster pipeline 並將繪製相關操作直接提交給 GPU,無需任何原生程式碼,創建專門的渲染器,例如:2D Canvas 替代方案、3D 場景、粒子系統。

Flutter GPU 入門指南

engine/docs/impeller/Flutter-GPU.md at main · flutter/engineThe Flutter engine. Contribute to flutter/engine development by creating an account on GitHub.github.com

使用 flutter_scene 渲染的太空頭盔
使用 flutter_scene 渲染的太空頭盔
https://x.com/algebrandon/status/1735907945467294020

✔️Flutter Scene

針對沒有圖形開發經驗的開發人員來說,官方提供了由 Flutter GPU 開發的 3D 渲染套件 flutter_scene package。可以利用 Flutter GPU API 來導入動畫 glTF 模型,進而構建 3D 場景,使我們能夠在 Flutter 和 Dart 中輕鬆實現 3D 應用程式和遊戲。

Flutter Scene入門指南

flutter_scene | Flutter package3D scene widgets for Flutter.pub.dev

目前 Flutter GPU 仍處於早期預覽階段,隨時可能會對 API 進行重大更新。官方建議在使用 Flutter GPU 時請在 master channel 進行開發。

Improved defaults for downscaled images#

Image 的預設值 FilterQuality已從FilterQuality.low 更新為FilterQuality.medium。原因是,當小的顯示區域載入大型圖像時,FilterQuality.low會導致圖像看起來更加“像素化”,並且渲染速度更慢。

Flutter Web: Multi-view Embedding#

本次提供的新功能, 稱為 “embedded mode” 和 “multi-view”,可以利用多視圖嵌入,同時將 Flutter 內容渲染到多個 HTML 元素中。提供整合到原有 Web 應用的靈活性,對於需要多個獨立 Flutter View 的複雜 Web 應用特別有用。啟用多視圖模式,需要設置 multiViewEnabled: true。

  1. Flutter Web 不會在啟動後立即顯示,它會等到本地應用使用 addView() 方法添加第一個 View
  2. Host 應用程式可以動態新增或刪除這些 View,每次操作都會觸發 Flutter 內的更新,從而允許動態內容渲染
  3. 支援每個 View 的自訂初始化數據,從而實現個人化配置和互動式體驗
// flutter_bootstrap.js
{{flutter_js}}
{{flutter_build_config}}

_flutter.loader.load({
  onEntrypointLoaded: async function onEntrypointLoaded(engineInitializer) {
    let engine = await engineInitializer.initializeEngine({
      multiViewEnabled: true, // Enables embedded mode.
    });
    let app = await engine.runApp();
    // Make this `app` object available to your JS app.
  }
});

Embedding Flutter on the webLearn the different ways to embed Flutter views into web content.docs.flutter.dev

Flutter for iOS and macOS#

Swift Package Manager (SPM)#

提供了 Swift Package Manager 的 early support,鼓勵套件作者為專案添加對 SPM 的支援,為已支援 CocoaPods 的專案新增 Swift Package Manager 支援。有效簡化 Flutter 安裝過程,對於不熟悉 iOS 生態系統的開發者,幫助他們減少學習成本。接下來,無需安裝 Ruby 和 CocoaPods,也可以在 Apple 平台上運行 Flutter 應用。

官方有提供 Swift 和 Object C 的教學說明。

Swift Package Manager for plugin authorsHow to add Swift Package Manager compatibility to iOS and macOS pluginsdocs.flutter.dev

Cupertino Design#

本次解決了整個 Cupertino 的15 個問題,並在 Widget library 添加了37 個缺少的 Cupertino 元件。

官方為 macOS 應用添加了 Platform View 和 WebView 支援,允許原生 macOS UI 整合到 Flutter 應用程式中,以獲得更完整、更精緻的用戶體驗。

Hosting native macOS views in your Flutter app with Platform ViewsLearn how to host native macOS views in your Flutter app with Platform Views.docs.flutter.dev

Embedding web content into a Flutter web appLearn how to load and display images on the web.docs.flutter.dev

Flutter APP Icon#

Flutter 3.24 的預設 App Icon

https://x.com/RayLiVerified/status/1820960116449144998/photo/1

Monetization: Video ad monetization support#

新的 interactive_media_ads (IMA) 套件,支援 Instream 插播廣告並進行獲利,有效幫助產品最大限度地提高收入。允許在影片的前中後進行廣告插播,另外有一些廣告也可以跳過。

優點:

  • 在影片播放器上無縫獲利
  • Google 廣告需求和行業標準合規性(例如:IAB VAST)

此版本目前支援 Android 和 iOS 平台的前置影片廣告。

interactive_media_ads | Flutter packageA Flutter plugin for using the Interactive Media Ads SDKs on Android and iOS.pub.dev

Future<void> _requestAds(AdDisplayContainer container) {
  _adsLoader = AdsLoader(
    container: container,
    onAdsLoaded: (OnAdsLoadedData data) {
      final AdsManager manager = data.manager;
      _adsManager = data.manager;

      manager.setAdsManagerDelegate(AdsManagerDelegate(
        onAdEvent: (AdEvent event) {
          debugPrint('OnAdEvent: ${event.type}');
          switch (event.type) {
            case AdEventType.loaded:
              manager.start();
            case AdEventType.contentPauseRequested:
              _pauseContent();
            case AdEventType.contentResumeRequested:
              _resumeContent();
            case AdEventType.allAdsCompleted:
              manager.destroy();
              _adsManager = null;
            case AdEventType.clicked:
            case AdEventType.complete:
          }
        },
        onAdErrorEvent: (AdErrorEvent event) {
          debugPrint('AdErrorEvent: ${event.error.message}');
          _resumeContent();
        },
      ));

      manager.init();
    },
    onAdsLoadError: (AdsLoadErrorData data) {
      debugPrint('OnAdsLoadError: ${data.error.message}');
      _resumeContent();
    },
  );

  return _adsLoader.requestAds(AdsRequest(adTagUrl: _adTagUrl));
}

Ecosystem: Shared Preferences#

針對shared_preferences 套件新增了兩個新的API。

  1. SharedPreferencesAsync:允許直接取得裝置上儲存最新的 preferences,但代價是非同步運行,並且比使用快取版本還慢。有利於其他系統或 isolate 的更新方式,缺點是可能會導致快取失效
  2. SharedPreferencesWithCache: 建構在 SharedPreferencesAsync 之上,允許同步地存取原生快取。與舊的 API 類似,但現在可以使用不同的參數多次實例化

實際上 Android 使用 Preferences DataStore 而不是 Shared Preferences

DevTools and IDEs#

Performance: Rebuild Stats#

可以捕獲元件建立的數量與相關資訊,檢查是否建立了比預期更多、消耗更大的成本。

Flutter Sidebar#

在 VS Code IDE 中的改進,讓開發者更輕鬆地操作。

DevTools extensionsLearn how to use and build DevTools extensions.docs.flutter.dev

Flutter Global Impact#

Contributor#

本次版本由超過 167 位獨立貢獻者(其中包括49位新貢獻者)的近 1,500 次提交組成。

Enterprise#

有更多大型企業使用 Flutter 作為產品開發的首選。

  1. 小米 (中國),SU7 電動車相關應用

Flutter Showcase | XiaomiTake a look at how and why a small team at Chinese technology company, Xiaomi, used Flutter to develop a companion app…flutter.dev

\2. SNCF Connect (法國),最大的鐵路交通應用

Flutter Showcase | SNCF ConnectSNCF Connect is the all-in-one mobility service, designed and developed by SNCF Connect & Tech. With more than 1.3…flutter.dev

\3. Wolt (荷蘭),零售配送應用

Flutter Showcase | WoltWolt, a part of Doordash International since 2022, makes it easy to get the best restaurant food, groceries, gifts and…flutter.dev

\4. Whirlpool (巴西),電子商務應用

Flutter Showcase | WhirlpoolFor more than 100 years, Whirlpool has manufactured home appliances designed to improve life at home. Now a Fortune 500…flutter.dev

\5. Monta (丹麥),電動車應用

Flutter Showcase | MontaMonta delivers software solutions for the entire EV charging ecosystem, connecting drivers, businesses, and industry…flutter.dev

Project IDX#

現在建立專案時可以選擇任何的模板與範例。

Breaking changes and deprecations#

此版本中的重大變更包括已棄用的 API。可以使用 Dart CLI 解決修復工作,或是直接從新的 IDE 功能執行。

dart fix

若要查看所有受影響的 API 以及其他相關資訊,請查慨 3.19 棄用指南。

Breaking changes and migration guidesA list of migration guides for breaking changes in Flutter.docs.flutter.dev


Flutter 版本升級🔝#

flutter upgrade

本文原刊登於 Medium。