[英]ListTile single selection (Flutter)
當然,這是一個簡單的解決方案,但我無法弄清楚 - 我在 flutter 中還是很新的 - 仍然。 有什么問題?
我有帶有 4 個列表圖塊的警報對話框,這些圖塊應該用作 gps 半徑的選擇器,但是我遇到了單選問題。 現在,當一個被選中時——所有的都是同時被選中的。 所以我需要找到一種方法如何為它們中的每一個進行單一選擇(如果選擇了 rest 應該取消選擇),然后傳遞它的值,例如。 10、25 等,同時按下“選擇”按鈕。
class RadiusSelectorDialog extends StatefulWidget {
RadiusSelectorDialog({Key key}) : super(key: key);
@override
_RadiusSelectorDialogState createState() => _RadiusSelectorDialogState();
}
class _RadiusSelectorDialogState extends State<RadiusSelectorDialog>
with TitleDescriptionTextMixin {
bool selected = false;
@override
Widget build(BuildContext context) {
return AlertDialog(
scrollable: true,
contentPadding: EdgeInsets.all(4.0),
title: Center(child: smallerBoldText('Select radius:', fontSize: 15.0)),
content: Column(
children: [
Divider(
color: Colors.grey,
height: 2.0,
),
CustomListTile(
label: '10 km',
selected: selected,
onSelect: () => _onSelect(selected),
),
CustomListTile(
label: '25 km',
selected: selected,
onSelect: () => _onSelect(selected),
),
CustomListTile(
label: '50 km',
selected: selected,
onSelect: () => _onSelect(selected),
),
CustomListTile(
label: '75 km',
selected: selected,
onSelect: () => _onSelect(selected),
),
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(16.0))),
actions: [
FlatButton(
child: Text('Select',
style: TextStyle(
color: LegionColors.primaryRedHigh,
fontWeight: FontWeight.bold)),
onPressed: () {
Navigator.pop(context);
})
],
);
}
void _onSelect(bool value) {
setState(() {
if (selected == false) {
selected = true;
} else {
selected = false;
}
});
}
}
我的自定義 listTile 供選擇。
class CustomListTile extends StatelessWidget {
final String label;
final bool selected;
final Function onSelect;
const CustomListTile(
{Key key,
@required this.selected,
@required this.onSelect,
@required this.label})
: super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
ListTile(
title: Center(
child: Text(label,
style: selected == false
? TextStyle(color: Colors.black)
: TextStyle(
color: LegionColors.primaryRedHigh,
fontWeight: FontWeight.bold,
))),
selected: selected,
onTap: onSelect,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(16.0))),
),
Divider(
color: Colors.grey,
height: 2.0,
),
],
);
}
}
您正在使用相同的變量selected
來識別是否為所有項目選擇了該項目。 這是發生的事情,
selected
為了避免它
CustomListTile
中移動標識符並使其成為 StatefulWidget。Map
實現 HashMap<String, bool> selectedState = new HashMap();
void updateSelectionStatus(String selectedTileId, bool status) {
setState(() {
selectedState[selectedTileId] = status;
});
}
然后你可以像這樣使用它
CustomListTile(
label: '75 km',
selected: selectedState['your-unique-id'],
onSelect: () => updateSelectionStatus('your-unique-id', !selectedState['your-unique-id']),
)
在官方 Flutter 網站上查看其工作代碼https://api.flutter.dev/flutter/material/ListTile/selected.ZFC336EZ88388C67A2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.