I am trying to create a custom bottom sheet class to be re-usable, but it gives me the error of missing "State build" method. I know that I may include the @override method, but I have checked other responses like this, and I did not see the build method.
class ModalBottomSheet extends StatefulWidget {
final Function()? onPressed;
const ModalBottomSheet({Key? key, this.onPressed}) : super(key: key);
@override
State<ModalBottomSheet> createState() => _ModalBottomSheetState();
}
//error here
class _ModalBottomSheetState extends State<ModalBottomSheet> {
modal(context){
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context) {
return Container(
),
);
});
}
}
EDIT:
class ModalBottomSheet {
void modal(context) {
Function(int)? onPressed;
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context) {
return Container(
height: 200,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20)),
),
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
TextButton(
onPressed: (1) {
onPressed?.call();
},
child: Text(
'CAMERA',
),
),
TextButton(
onPressed: (2) {
onPressed?.call();
},
child: Text(
'GALLERY',
),
),
This is the Main screen where to show the custom modal sheet:
ModalBottomSheet.modal(context,
onPressed: (index){
if(index == 1){
pickImage(ImageSource.camera);
}else{
pickImage(ImageSource.gallery);
}
});
You are extending the StatefulWidget
, which requires you to override the build
method. Instead, you can create a class or mixin that doesn't extend Widget
, it will have a method that shows modal and requires BuildContext
as a function parameter.
class ModalBottomSheet {
void modal(context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context) {
return ...
},
);
}
}
Edit:
You can also pass other parameters to this function, as void Function()? onPressed
.
class ModalBottomSheet {
static void modal(BuildContext context, void Function()? onPressed) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context) {
return ...;
},
);
}
}