ElavatedButton
亦可設定成背景為 漸層色
,但必須搭配 Container
與 BoxDecoration
才能實現。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
ElavatedButton
搭背背景竟層色
ElavatedButton
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
const Home({super.key});
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('ElevatedButton'),
);
var elevatedButton = Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
begin: Alignment(1, 0),
end: Alignment(-1.00, 0.00),
colors: [Color(0xFF359AD2), Color(0xFF7FB6DE)],
),
borderRadius: BorderRadius.circular(8),
),
child: ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('ElevatedButton Pressed!'),
),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
child: const Text(
'Press Me',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
);
var body = Center(
child: elevatedButton,
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 12
var elevatedButton = Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
begin: Alignment(1, 0),
end: Alignment(-1.00, 0.00),
colors: [Color(0xFF359AD2), Color(0xFF7FB6DE)],
),
borderRadius: BorderRadius.circular(8),
),
child: ElevatedButton(
)
);
Container
:無法由 style 直接將ElavatedButton
的背景設定為漸層色,必須在外層包一層Container
,並由decoration
設定漸層色decoration
:由BoxDecoration
內的gradient
設定漸層色borderRadius
:亦可在BoxDecoration
內設定圓角
Line 29
style: ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
style
:由ElevatedButton.styleFrom()
設定ElavatedButton
的 stylebackgroundColor
:由於背景顏色已經被Container
接管,因此必須將ElavatedButton
自己的 background 設定為transparent
,否則會影響到Container
所設定的漸層shadowColor
:也要設定成 transparent,否則會影響到Container
所設定的漸層padding
:設定內部 padding
Conclusion
- 無法直接在
ElavatedButton
設定背景漸層色,必須在外層搭配Container
,在BoxDecoration
設定LinearGradient
- 由於
背景顏色
已經被外層的Container
接管,必須將原本ElavatedButton
自己 style 的backgroundColor
與shadowColor
都設定成transparent
,否則會影響BoxDecoration
的漸層色