ARK1375
ARK1375

Reputation: 818

How to send a "button is pressed signal" to a higher class in widget tree hierarchy in flutter?

In my app tree hierarchy, I have a Stateful widget that represents the elements of a list. Let's call this class Item. This Widget contains an Image, some text, and a remove button that should remove the element when it's pressed. Later in the code, I have another Stateful class that holds the ListView and a List of Item which the ListView is created based on it.
My problem is that the onPressed() attribute of every Item is placed inside the item's class and not the upper class (the ListView) in which the remove operation should be handled. How can I fix this? How can I send a signal whenever the button is pressed to the parent widget in order to initiate removing the item?

import 'package:flutter/material.dart';

class Item extends StatefulWidget {
  const Item({ Key? key }) : super(key: key);

  @override
  _ItemState createState() => _ItemState();
}

class _ItemState extends State<Item> {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: [
          Image(),
          Text('abc'),
          Text('abc'),
          Text('abc'),
          ElevatedButton(onPressed: ????? , child: Text('RemoveButton'))
        ],),
    );
  }
}


class ListOfItems extends StatefulWidget {
  const ListOfItems({ Key? key }) : super(key: key);

  @override
  _ListOfItemsState createState() => _ListOfItemsState();
}

class _ListOfItemsState extends State<ListOfItems> {

  List<Item> ls = [];
  int numOfItems = 0;


  @override
  Widget build(BuildContext context) {
    return ListView(children: ls,)
  }
}

Upvotes: 0

Views: 393

Answers (1)

kzrfaisal
kzrfaisal

Reputation: 1443

Try like this

import 'package:flutter/material.dart';

class Item extends StatefulWidget {
  final void Function(dynamic data) onPressedHandler;
  const Item({ @required this.onPressedHandler, Key? key }) : super(key: key);

  @override
  _ItemState createState() => _ItemState();
}

class _ItemState extends State<Item> {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: [
          Image(),
          Text('abc'),
          Text('abc'),
          Text('abc'),
          ElevatedButton(onPressed: () {
            final data = 'Any additional data you want to paas';
            widget.onPressedHandler(data);
          } , child: Text('RemoveButton'))
        ],),
    );
  }
}


class ListOfItems extends StatefulWidget {
  const ListOfItems({ Key? key }) : super(key: key);

  @override
  _ListOfItemsState createState() => _ListOfItemsState();
}

class _ListOfItemsState extends State<ListOfItems> {

  List<Item> ls = [];

  int numOfItems = 0;

  onPressedHandler(data) {

  }

  @override
  Widget build(BuildContext context) {
    return ListView(children: [
      Item(onPressedHandler: onPressedHandler),
    ],);
  }
}

Upvotes: 1

Related Questions