这实际上有点困难 - 正如你提到的 CupertinoSliverAppBar 不支持'flexibleSpace'或类似的东西,所以你被困在尝试使用也不能满足你需要的背景颜色。
我建议在 Flutter 存储库上打开一个问题,说明这是不可能的以及你为什么要这样做。他们可能不会立即采取行动,但如果他们知道人们愿意这样做,它可能会发生。
不过,并不是所有的希望都立即修复,我们可以作弊!(尽管我希望您在编写版本时使用不那么丑陋的渐变)
我所做的是子类化边框,然后覆盖它绘制的内容,以便在绘制实际边框之前绘制你传入的渐变。这是有效的,因为它被赋予了一个覆盖整个应用栏的绘制上下文,并在应用栏的背景上绘制,但在其内容下方(希望 - 它似乎至少在标题下方,所以我认为它也在其他所有内容下方)。背景颜色仍绘制在应用栏下方,因此如果您的渐变有点透明,您可能需要将 backgroundColor 设置为 Colors.transparent。
这是代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(GradientAppBar());
class GradientCheatingBorder extends Border {
const GradientCheatingBorder({
this.gradient,
BorderSide top = BorderSide.none,
BorderSide right = BorderSide.none,
BorderSide bottom = BorderSide.none,
BorderSide left = BorderSide.none,
}) : super(top: top, right: right, bottom: bottom, left: left);
const GradientCheatingBorder.fromBorderSide(BorderSide side, {this.gradient})
: super.fromBorderSide(side);
factory GradientCheatingBorder.all({
Color color = const Color(0xFF000000),
double width = 1.0,
BorderStyle style = BorderStyle.solid,
Gradient gradient,
}) {
final BorderSide side =
BorderSide(color: color, width: width, style: style);
return GradientCheatingBorder.fromBorderSide(side, gradient: gradient);
}
final Gradient gradient;
@override
void paint(
Canvas canvas,
Rect rect, {
TextDirection textDirection,
BoxShape shape = BoxShape.rectangle,
BorderRadius borderRadius,
}) {
if (gradient != null) {
canvas.drawRect(
rect,
Paint()
..shader = gradient.createShader(rect)
..style = PaintingStyle.fill,
);
}
super.paint(
canvas,
rect,
textDirection: textDirection,
shape: shape,
borderRadius: borderRadius,
);
}
}
class GradientAppBar extends StatefulWidget {
@override
_GradientAppBarState createState() => _GradientAppBarState();
}
class _GradientAppBarState extends State<GradientAppBar> {
@override
Widget build(BuildContext context) {
return CupertinoApp(
home: CustomScrollView(
slivers: <Widget>[
CupertinoSliverNavigationBar(
largeTitle: Text("Title"),
border: GradientCheatingBorder.fromBorderSide(
BorderSide.none,
gradient: LinearGradient(colors: [Colors.black, Colors.white]),
),
),
SliverList(
delegate: SliverChildListDelegate(
[
Container(
color: Colors.blue,
height: 500,
),
Divider(),
Container(
color: Colors.black12,
height: 500,
),
Divider(),
Container(
color: Colors.lightBlue,
height: 500,
),
Divider(),
Container(
color: Colors.lightGreen,
height: 500,
),
Divider(),
],
),
),
],
),
);
}
}