在Flutter中,你可以使用BoxDecoration
和LinearGradient
来创建一个带有渐变背景的AppBar
。以下是一个简单的例子:
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget with PreferredSizeWidget {
final String title;
final List<BoxShadow> boxShadow;
final Gradient gradient;
const MyAppBar({
Key key,
this.title = '',
this.boxShadow = const <BoxShadow>[
BoxShadow(
color: Colors.black26,
blurRadius: 10.0,
spreadRadius: 0.0,
offset: Offset(0.0, 10.0),
),
],
this.gradient = const LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Color(0xff614385),
Color(0xff516395),
],
),
}) : preferredSize = Size.fromHeight(kToolbarHeight), super(key: key);
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title),
elevation: 0.0,
backgroundColor: Colors.transparent,
toolbarHeight: kToolbarHeight,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(10.0),
),
),
actions: <Widget>[
// Add your actions here
],
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: MyAppBar(title: 'Gradient AppBar'),
body: Center(
child: Text('Your content goes here'),
),
),
);
}
}
在这个例子中,MyAppBar
类继承了PreferredSizeWidget
并且定义了一个渐变效果的AppBar
。LinearGradient
定义了渐变的色彩和方向,并被用在BoxDecoration
中作为AppBar
的背景。这个AppBar
还有圆角和阴影效果。