Я искал несколько часов, чтобы не пропустить.У меня есть ListView, который построен с помощью этого конструктора
ListView.builder(
itemCount: 5,
itemBuilder: (context, int index) {
return ServiceCard(index: index,);
},
),
, теперь в виджете ServiceCard У меня есть кнопка, чтобы удалить текущий виджет в дереве ListView, например, третий виджет ServiceCard.
Перепробовал много методов, которые не работали.Я удивлен, что даже документация флаттера не показывает, как реализовать такую общую функциональность.
Я попытался дать ListView переменную, чтобы я мог получить к ней доступ и удалить из нее нужный виджет.к сожалению нет такой функциональности.
Я попытался дать ListView подготовленный виджет ListCardCard, который я затем использовал, чтобы использовать его длину для itemCounter объекта ListView.затем удаление элемента из списка в setState кнопки на указанном виджете ServiceCard.
Я попытался использовать метод, который принимает индекс в качестве аргумента и возвращает ServiceCard только в случае, когда текущий индекс равенравен индексу удаленного элемента.к сожалению, это удаляет последнюю ServiceCard, а не назначенную.
вот виджет ServiceCard:
class ServiceCard extends StatefulWidget {
ServiceCard({this.index});
int index;
@override
_ServiceCardState createState() => _ServiceCardState();
}
class _ServiceCardState extends State<ServiceCard> {
void onFormSubmitted() {
var form = formKey.currentState;
if (form.validate()) {
form.save();
}
}
@override
Widget build(BuildContext context) {
int index = widget.index;
return Container(
height: 440,
child: Column(
children: <Widget>[
ExpandableRoundRectangleContainer(
widgetList: <Widget>[
Container(
height: 370,
child: Stack(
alignment: Alignment.bottomLeft,
children: <Widget>[
//column for tow TextField with headers
Column(
children: <Widget>[
HeaderTextWithFormTextFieldAndSizedBox(
headerText: 'Service Name',
hintText: 'Write your service name here...',
autoFocus: true,
iconData: Icons.info_outline,
validatorFunction: (String value) {
if (value.length > 0 && value.length < 6) {
return '*Service name should be more than 5 letters';
} else if (value.length == 0) {
return '* Service name is required';
}
},
onSaved: (String value) {},
),
HeaderTextWithFormTextFieldAndSizedBox(
headerText: 'Service Description',
hintText: 'Write your service description here...',
autoFocus: false,
iconData: Icons.info_outline,
validatorFunction: (String value) {
if (value.length > 0 && value.length < 6) {
return '* Service description should be more than 5 letters';
} else if (value.length == 0) {
return '* Service description is required';
}
},
letterCount: 200,
maxLines: 3,
contentPadding: 13,
onSaved: (String value) {},
),
],
),
//only add the add service button when it is the last card
Visibility(
// visible: widget.index == serviceNamesList.length - 1 ,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: RoundButtonWithIconFix(
text: 'Add Another Service',
buttonWidth: 160,
buttonColor: kAppLightBlueColor,
onButtonPressed: () {},
icon: Icons.add_box,
color: Colors.white,
iconTextSpacing: 5,
iconSize: 25,
),
),
),
Positioned(
bottom: 50,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: RoundButtonWithIconFix(
text: 'Remove Service',
buttonWidth: 130,
buttonColor: kAppLightBlueColor,
onButtonPressed: () {
setState(() {
});
},
icon: Icons.delete,
color: Colors.white,
iconTextSpacing: 5,
iconSize: 25,
),
),
),
],
),
),
],
),
Visibility(
// visible: widget.index == serviceNamesList.length - 1 ,
child: DoneButton(
onPressed: onFormSubmitted,
),
),
],
),
);
}
}