🧑💻
FlutterのSliverAppBarを使ってみよう!
あなたはSliverAppBarを使ったことはありますか?
これを使うとアプリをスクロールさせた時に変化したり、消したりするヘッダーを作ることができます。SliverAppBarはCustomScrollViewと一緒に使われ、AppBarにカスタムスクロール動作を加えてくれます。
CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text('SliverAppBar');
),
]
)
Sliverは細長い小片という意味で、実行中のスクロールが可能な範囲上で細かいコントロールを提供してくれるものです。
flexibleSpaceパラメータは、expandedHeightパラメータと連携しています。そのため、この両方を設定して最大サイズに拡張した時のAppBarの高さと外観を変えられます。
SliverAppBar(
expandedHeight: 200.0,
flexibleSpace: FlexibleSpaceBar(
background: _expandedImage,
),
),
floatingパラメータをtrueに設定し、下にスクロールするときにリスト最上部に達しなくてもアプリ画面を再表示させられます。
SliverAppBar(floating: true)
サンプルプログラム
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
const title = 'Floating App Bar';
return MaterialApp(
title: title,
home: Scaffold(
body: CustomScrollView(
slivers: [
const SliverAppBar(
title: Text(title),
floating: true,
flexibleSpace: Placeholder(),
expandedHeight: 200,
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item #$index')),
childCount: 1000,
),
),
],
),
),
);
}
}
Discussion