alpha Lounge

20%の技術記事とオタクネタ

【Flutter】RepaintBoundaryによるパフォーマンス向上について【Tips】

Flutterのパフォーマンスを上げる方法の一つである「RepaintBoundary」Widgetについて軽くメモ。

説明

公式の資料はこちら。こちらに説明全て書いてありますが😇

api.flutter.dev

FlutterはWidgetが再描画されると、関連する同じレイヤーのWidgetが再描画されます。状況によっては再描画の必要のないWidgetまで再描画され、パフォーマンスの低下を招きます。 RepaintBoundaryを使用すると、子Widgetの描画を分離させ、再描画を防ぐことができます。

アプリを作っている側としては、基本的に「再描画のタイミングが異なるWidgetを囲むことでパフォーマンスを上げる」と認識しておけばOKかと思います。


具体的には以下のような活用がありました。

CustomPaintへの使用

任意の図形を描画できるCustomPaint Widgetですが、再描画が走るとパフォーマンスに影響が出ることがあります。RepaintBoundaryを使用して描画処理を切り離します。

 
  Widget buildCustomPaint() {
    return RepaintBoundary(
      child: CustomPaint(
        painter: ExpansivePainter(),
        isComplex: true,
        willChange: false,
      ),
    );
  }

アニメーション内部のWidgetを囲む

Flutterのベンチマークで行っている手法です。アニメーションを行うWidgetで、アニメーション内のWidgetの再描画を防ぐために使用します。

// https://github.com/flutter/flutter/blob/1704d4f5f9c2f53decd1d526a8a41dfa06d1e484/dev/benchmarks/macrobenchmarks/lib/src/color_filter_and_fade.dart#L63

final Widget fadeTransition = FadeTransition(
  opacity: _opacityAnimation,
  // This RepaintBoundary is necessary to not let the opacity change
  // invalidate the layer raster cache below. This is necessary with
  // or without the color filter.
  child: RepaintBoundary(
    child: column,
  ),
);

まとめ

通常の開発ではRepaintBoundaryを使う機会はあまりないかもしれませんが、パフォーマンスが気になるとなった時に、上記の観点を意識して試してみるとよさそうです👍

参考資料:
Dive in to DevTools - YouTube
Flutter - Using RepaintBoundary Examples - Woolha
Flutter-タイマーアプリケーションを作ってみる6 | Take4-blue
FlutterのRaster Cacheを追ってみる