Flutter

AppBarの背景をグラデーションにする

Flutter Widget Basics AppBar

AppBarでは背景色を指定できるが、それにグラデーションを効かせたい。しかし、AppBarのcolorにはGradientを設定できないのでAppBarをラップしたGradientAppBarを実装してみる。

PreferredSizeWidget

StatelessWidgetをextendsした新しいクラスを定義したいが、ScaffoldのappBarのクラスはPreferredSizeWidgetで宣言されているため、PreferredSizeWidgetのinterfaceを実装しておく必要がある。

そこでGradientAppBarclassはPreferredSizeWidgetをimplementsしてpreferredSizeをoverrideする。GradientとAppBarをメンバ変数とし、指定できるようにする。preferredSizeはAppBarのpreferredSizeをそのまま使う。

GradientAppBarの使用例

GradientAppBarを実際に使ってみた例。

gradientにLinearGradientをtopCenterからtopBottomへのグラデーションとし、カラーを二色設定した。

Flutterを使ったアプリをリリースしてます。良ければ使ってみてください。