Home > Mobile >  Assign a <Widget>[] array as the child parameter to a Dismissible() object
Assign a <Widget>[] array as the child parameter to a Dismissible() object

Time:01-02

I've been trying to make a content group (image text) Dismissible as a single unit (swipe-to-delete/remove), but seems as though I can't assign a Widget list as the child parameter to a Dismissible() object. Looking for possible work-arounds or a solution to the problem.

CODE:

class _PhotosListState extends State<PhotosList> {
  @override
  Widget build(BuildContext context) {
    return _buildBody();
  }
  Widget _buildBody() {
    return SizedBox(
        height: 485,
        child: ListView.builder(
          //scrollDirection: Axis.vertical,
          //shrinkWrap: true,
            itemCount: Photos.length,
            itemBuilder: (context,i){
              return Dismissible(
                  background: Container(
                    color: Colors.green,
                  ),
                  key: ValueKey<Object>(Photos.items[i]),
                  onDismissed: (DismissDirection direction) {
                    setState(() {
                      Photos.items.removeAt(i);
                    });
                  },
                  child: SizedBox(
                    child: <Widget> [
                      Image.asset(Photos.items[i].image),
                      Text(Photos.items[i].task,
                          textAlign: TextAlign.center,
                          style: const TextStyle(color: Colors.grey, fontWeight: FontWeight.bold, fontSize: 19.5)
                      ),
                    ]
                  )
              );
            }
        )
    );
  }
}

RESOURCES:

CodePudding user response:

In your code of SizedBox:

SizedBox(
                    child: <Widget> [
                      Image.asset(Photos.items[i].image),
                      Text(Photos.items[i].task,
                          textAlign: TextAlign.center,
                          style: const TextStyle(color: Colors.grey, fontWeight: FontWeight.bold, fontSize: 19.5)
                      ),

you are passing multiple widgets as a child, but child only takes one argument (i.e, one widget).

So, if you want multiple widgets, you should use a Column widget instead - which can accept a List:

SizedBox(
                      child: Column(children: <Widget>[
                    Image.asset(Photos.items[i].image),
                    Text(Photos.items[i].task,
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                            color: Colors.grey,
                            fontWeight: FontWeight.bold,
                            fontSize: 19.5)),
                  ]))

Hence the names - child vs children - it's good to keep this in mind as there can be widgets the accept multiple widgets, i.e. children or a widget that can only accept one child.

  • Related