颤振-检查是否SliverAppBar

时间:2020-11-11 18:28:43

标签: flutter dart flutter-sliver

我希望在SliverAppBar折叠时在FlexSpace中更改标题的填充。 有没有办法做到这一点?

Scaffold(
  body: CustomScrollView(
    slivers: <Widget>[
      SliverAppBar(
        expandedHeight: 150.0,
        flexibleSpace: const FlexibleSpaceBar(
          //I want to change the padding to 40 when the SliverAppBar collapsed
          titlePadding: EdgeInsets.only(left: 10),
          title: Text('Available seats'),
        ),
      ),
    ],
  ),
);

1 个答案:

答案 0 :(得分:1)

您可以在SliverPersistentHeaderDelegate内创建自己的FlexibleSpaceBar

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverPersistentHeader(delegate: CustomSliverAppBar()),
          SliverToBoxAdapter(
            child: Container(
              height: 1300,
              color: Colors.amber,
            ),
          )
        ],
      ),
    );
  }
}

class CustomSliverAppBar extends SliverPersistentHeaderDelegate {
  @override
  Widget build(context, shrinkOffset, overlapsContent) {
    return AppBar(
      flexibleSpace: FlexibleSpaceBar.createSettings(
        maxExtent: maxExtent,
        minExtent: minExtent,
        child: FlexibleSpaceBar(
          titlePadding: EdgeInsets.only(
            left: srinkRate(shrinkOffset) == 1 ? 40 : 10,
          ),
          title: Text(
              srinkRate(shrinkOffset) == 1 ? 'shrinked' : 'Available seats'),
        ),
        currentExtent: (maxExtent - shrinkOffset).clamp(minExtent, maxExtent),
      ),
    );
  }

  @override
  double get maxExtent => 150.0;

  @override
  double get minExtent => 50;

  double get delta => maxExtent - minExtent;

  double srinkRate(double shrinkOffset) =>
      (shrinkOffset / delta).clamp(0.0, 1.0);

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      true;
}