den*_*gas 9 flutter flutter-layout
如何在flutter中更改PopupMenuItem的背景颜色?
现在我只是改变 PopupMenuItem 子项的颜色,结果是这样的:

这是代码:
PopupMenuButton<int>(
onSelected: (value) {
// TODO: Implement onSelect
},
offset: Offset(50, 50),
itemBuilder: (context) => [
PopupMenuItem(
value: 1,
child: Container(
height: double.infinity,
width: double.infinity,
color: Colors.greenAccent, // i use this to change the bgColor color right now
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Icon(Icons.check),
SizedBox(width: 10.0),
Text("Konfirmasi Update"),
SizedBox(width: 10.0),
],
),
),
),
Run Code Online (Sandbox Code Playgroud)
我想要的是更改“Konfirmasi Update”选项的背景颜色,如上图所示,颜色在选项外留下白色区域。
如何完全更改 PopupMenuItem 背景颜色,而不留下 PopupMenuItem 外部的白色区域?
小智 16
另一种选择是从 PopupMenuItem 继承。
要使用,只需更改 CustomPopupMenuItem 的 PopupMenuButton 并设置颜色。
import 'package:flutter/material.dart';
class CustomPopupMenuItem<T> extends PopupMenuItem<T> {
final Color color;
const CustomPopupMenuItem({
Key key,
T value,
bool enabled = true,
Widget child,
this.color,
}) : super(key: key, value: value, enabled: enabled, child: child);
@override
_CustomPopupMenuItemState<T> createState() => _CustomPopupMenuItemState<T>();
}
class _CustomPopupMenuItemState<T> extends PopupMenuItemState<T, CustomPopupMenuItem<T>> {
@override
Widget build(BuildContext context) {
return Container(
child: super.build(context),
color: widget.color,
);
}
}
Run Code Online (Sandbox Code Playgroud)
无法开箱即用地使用PopupMenuButton和PopupMenuItem小部件,因为如果您检查源代码,就会发现垂直和水平填充的硬编码值。
我修改了文件的代码popup_menu.dart,特别是这些值:
const double _kMenuVerticalPadding = 0.0;//8.0;
const double _kMenuHorizontalPadding = 0.0;//16.0;
Run Code Online (Sandbox Code Playgroud)
如果您想让它工作,请将此文件下载到您的项目:https://gist.github.com/diegovoper/995f1e03ef225edc64e06525dc024b01
将该文件导入到您的项目中并添加别名:
import 'your_project/my_popup_menu.dart' as mypopup;
Run Code Online (Sandbox Code Playgroud)
用法:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: mypopup.PopupMenuButton<int>(
elevation: 20,
onSelected: (value) {
// TODO: Implement onSelect
},
offset: Offset(50, 50),
itemBuilder: (context) => [
mypopup.PopupMenuItem(
value: 1,
child: Container(
height: double.infinity,
width: double.infinity,
color: Colors
.greenAccent, // i use this to change the bgColor color right now
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Icon(Icons.check),
SizedBox(width: 10.0),
Text("Konfirmasi Update"),
SizedBox(width: 10.0),
],
),
),
),
mypopup.PopupMenuItem(
value: 1,
child: Container(
height: double.infinity,
width: double.infinity,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Icon(Icons.check),
SizedBox(width: 10.0),
Text("Revisi Update"),
SizedBox(width: 10.0),
],
),
),
),
],
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
结果
| 归档时间: |
|
| 查看次数: |
11118 次 |
| 最近记录: |