我试图创建一个自定义的底部表类是可重用的,但它给了我的错误缺少"状态构建"方法。我知道我可以包括@override方法,但我检查了其他类似的响应,我没有看到构建方法。
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(
),
);
});
}
}
编辑:
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',
),
),
主界面在哪里显示自定义模态表:
ModalBottomSheet.modal(context,
onPressed: (index){
if(index == 1){
pickImage(ImageSource.camera);
}else{
pickImage(ImageSource.gallery);
}
});
您正在扩展StatefulWidget
,这需要您覆盖build
方法。相反,你可以创建一个不扩展Widget
的类或mixin,它将有一个显示模态的方法,并需要BuildContext
作为函数参数。
class ModalBottomSheet {
void modal(context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context) {
return ...
},
);
}
}
编辑:
您也可以将其他参数传递给该函数,如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 ...;
},
);
}
}