개발/Flutter
커스텀 위젯(Custom Widget)
파란검정
2023. 4. 6. 00:16
반응형
StatelessWidget 또는 StatefulWidget 클래스를 상속받습니다.
build 메소드를 오버라이드하고, 위젯의 모양과 동작을 정의합니다.
필요에 따라 StatefulWidget을 사용하여 위젯의 상태를 관리할 수 있습니다.
위젯을 사용할 때는 해당 위젯의 클래스명을 호출하면 됩니다.
아래는 간단한 커스텀 위젯을 만드는 예시 코드입니다.
import 'package:flutter/material.dart';
class MyButton extends StatelessWidget {
final String text;
final Function onPressed;
MyButton({required this.text, required this.onPressed});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed as void Function()?,
child: Text(text),
);
}
}
.
위 코드에서는 MyButton이라는 커스텀 위젯을 만들었습니다.
이 위젯은 text와 onPressed 두 개의 파라미터를 받습니다.
text는 버튼에 표시될 텍스트를, onPressed는 버튼이 클릭되었을 때 호출될 함수를 전달합니다.
위젯 내부에서는 ElevatedButton 위젯을 사용하여 버튼을 구현하였습니다.
onPressed와 child 속성을 MyButton에서 전달받은 onPressed와 text 파라미터로 설정하였습니다.
이렇게 만든 MyButton 위젯은 다음과 같이 사용할 수 있습니다.
MyButton(
text: 'Click me!',
onPressed: () {
print('Button clicked!');
},
),
위 코드에서는 MyButton 위젯을 생성하고, text와 onPressed 파라미터를 전달하였습니다.
onPressed 파라미터에는 클릭 시 호출될 함수를 정의하였습니다.
반응형