기본 스타일 지정
ElevatedButton(
child: Text('styleFrom'),
onPressed: (){},
// Set style using styleFrom
style: ElevatedButton.styleFrom(
primary: Colors.blue,
fixedSize: Size(200,50),
elevation: 20.0
)
)
위의 코드처럼 기본적으로 styleFrom()을 이용해서 버튼들의 스타일을 지정해 줄 수 있습니다.
이 방법은 워낙 기본적인 거라 다들 알거라고 생각합니다.
Press 유무에 따라 스타일 지정
ElevatedButton(
child: Text('ButtonStyle'),
onPressed: (){},
// Set style using ButtonStyle
style: ButtonStyle(
// Set backgroundColor depending on whether states is MaterialState.pressed
backgroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.pressed)
? Colors.green
: Colors.blue;
}),
// Set fixedSize depending on whether states is MaterialState.pressed
fixedSize: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.pressed)
? Size(300,100)
: Size(200,50);
}),
// Set elevation regardless of states
elevation: MaterialStateProperty.resolveWith((states) {
return 20.0;
}),
),
)
이 방법은 기존에 내가 몰랐던 방법이라 이렇게 기록해놓으려고 합니다.
ButtonStyle 내부에서 MaterialStateProperty를 사용해서 press시, hover시, focus시 등 여러 경우들에 대해서 스타일을 지정할 수가 있습니다. 위의 코드는 내가 press했을 때 스타일을 변경시키는 예시 코드입니다.
전체 예시 코드
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: PracticeButtonStyle(),
);
}
}
class PracticeButtonStyle extends StatefulWidget {
const PracticeButtonStyle({Key? key}) : super(key: key);
@override
State<PracticeButtonStyle> createState() => _PracticeButtonStyle();
}
class _PracticeButtonStyle extends State<PracticeButtonStyle> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
child: Text('ButtonStyle'),
onPressed: (){},
// Set style using ButtonStyle
style: ButtonStyle(
// Set backgroundColor depending on whether states is MaterialState.pressed
backgroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.hovered)
? Colors.green
: Colors.blue;
}),
// Set fixedSize depending on whether states is MaterialState.pressed
fixedSize: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.hovered)
? Size(300,100)
: Size(200,50);
}),
// Set elevation regardless of states
elevation: MaterialStateProperty.resolveWith((states) {
return 20.0;
}),
),
),
ElevatedButton(
child: Text('styleFrom'),
onPressed: (){},
// Set style using styleFrom
style: ElevatedButton.styleFrom(
primary: Colors.blue,
fixedSize: Size(200,50),
elevation: 20.0
)
)
],
)
),
);
}
}
이처럼 버튼을 스타일링 할 수 있다는 것을 확인할 수 있습니다.
https://docs.flutter.dev/release/breaking-changes/buttons
New Buttons and Button Themes
The basic material button classes have been replaced.
docs.flutter.dev