今天實(shí)現(xiàn)了一個(gè)自定義的ListViewDialog廉白, 先看看效果:
代碼如下:
import 'package:flutter/material.dart';
class ListViewDialog extends Dialog {
List<String> data;
double? width;
Function callback;
ListViewDialog({
Key? key,
required this.data,
required this.callback,
this.width,
}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Material(
//創(chuàng)建透明層
type: MaterialType.transparency, //透明類型
child: Center(
//保證控件居中效果
child: Container(
width: width ?? 400,
decoration: const BoxDecoration(
color: Color(0xff373737),
//設(shè)置四周圓角 角度
borderRadius: BorderRadius.all(Radius.circular(5.0)),
//設(shè)置四周邊框
),
child: ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: data.isEmpty ? 0 : data.length,
itemBuilder: (BuildContext context, int position) {
return itemWidget(context, position);
}),
),
),
// ),
);
}
Widget itemWidget(BuildContext context, int index) {
return TextButton(
child: Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.fromLTRB(10.0, 10.0, 0.0, 10.0),
child: Text(data[index],
),
),
),
style: ButtonStyle(
//更優(yōu)美的方式來(lái)設(shè)置 text 的顏色
foregroundColor: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.focused) &&
!states.contains(MaterialState.pressed)) {
//獲取焦點(diǎn)時(shí)的顏色
return Colors.blue;
} else if (states.contains(MaterialState.pressed)) {
//按下時(shí)的顏色
return const Color(0xff4D4D4D);
}
//默認(rèn)狀態(tài)使用灰色
return Colors.white;
},
),
//背景顏色
backgroundColor: MaterialStateProperty.resolveWith((states) {
//設(shè)置按下時(shí)的背景顏色
if (states.contains(MaterialState.pressed)) {
return Color(0xffDCDCDC);
}
//默認(rèn)不使用背景顏色
return null;
}),
//設(shè)置水波紋顏色
overlayColor: MaterialStateProperty.all(Color(0xff777777)),
//設(shè)置陰影 不適用于這里的TextButton
elevation: MaterialStateProperty.all(0),
//textbutton 默認(rèn)會(huì)有一個(gè)圓角 這里我們?nèi)サ魣A角
shape: MaterialStateProperty.all(
RoundedRectangleBorder()),
),
onPressed: () {
callback(index);
});
}
}
最后 使用如下:
showCustomDialog(BuildContext context ) {
showDialog(
context: context,
builder: (BuildContext context) {
return ListViewDialog(data: ["星期一","星期二","星期三","星期四"], width:300,callback: (selectIndex){
print(selectIndex);
});
});
}