要讓使用者在瀏覽list的時候更加方便,通常使用 Scaffold widget提供的 appBar 屬性來創建app bar會使app bar是固定的無法更改,但我們使用CustomScrollView
創建app bar可以解決app bar是固定的問題,總共需要3步
要創建浮動的app bar,請將app bar放在同時包含項目list的CustomScrollView
中
Scaffold(
// No appBar property provided, only the body.
body: CustomScrollView(
// Add the app bar and list of items as slivers in the next steps.
slivers: <Widget>[]),
);
使用 SliverAppBar widget新增浮動的app bar,其中flexibleSpace widget可以填充可用的expandedHeight到app bar讓app bar的初始高度比較高一點
CustomScrollView(
slivers: [
// Add the app bar to the CustomScrollView.
const SliverAppBar(
// Provide a standard title.
title: Text(title),
// Allows the user to reveal the app bar if they begin scrolling
// back up the list of items.
floating: true,
// Display a placeholder widget to visualize the shrinking size.
flexibleSpace: Placeholder(),
// Make the initial height of the SliverAppBar larger than normal.
expandedHeight: 200,
),
],
)
SliverList 和 SliverGrid widget都採用一個參數:SliverChildDelegate,它為 SliverList 或 SliverGrid 提供widget list
// Next, create a SliverList
SliverList(
// Use a delegate to build items as they're scrolled on screen.
delegate: SliverChildBuilderDelegate(
// The builder function returns a ListTile with a title that
// displays the index of the current item.
(context, index) => ListTile(title: Text('Item #$index')),
// Builds 1000 ListTiles
childCount: 1000,
),
)
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Floating App Bar';
return MaterialApp(
title: title,
home: Scaffold(
// No appbar provided to the Scaffold, only a body with a
// CustomScrollView.
body: CustomScrollView(
slivers: [
// Add the app bar to the CustomScrollView.
const SliverAppBar(
// Provide a standard title.
title: Text(title),
// Allows the user to reveal the app bar if they begin scrolling
// back up the list of items.
floating: true,
// Display a placeholder widget to visualize the shrinking size.
flexibleSpace: Placeholder(),
// Make the initial height of the SliverAppBar larger than normal.
expandedHeight: 200,
),
// Next, create a SliverList
SliverList(
// Use a delegate to build items as they're scrolled on screen.
delegate: SliverChildBuilderDelegate(
// The builder function returns a ListTile with a title that
// displays the index of the current item.
(context, index) => ListTile(title: Text('Item #$index')),
// Builds 1000 ListTiles
childCount: 1000,
),
),
],
),
),
);
}
}
參考資料:
https://docs.flutter.dev/cookbook/lists/floating-app-bar