Search code examples
flutterdart

How to extract from a column or row, an list of their widgets?


I have a column, is it possible to extract from it the list of children that are in this widget?

final listWidget = []; 
    listWidget.add(
      Column(children: [
        SizedBox(),
        SizedBox(),
        SizedBox(), 
      ],
    )); 

Can I extract a column from listWidget and then its children?

I thought I could conditionally do that:

listWidget[0].childrens.toList(); 

But unfortunately, that's not how it works


Solution

  • Running your example, you would get:

    error: The getter 'children' isn't defined for the type 'Widget'.
    

    since it doesn't know the correct type.

    To fix the issue, you can tell Dart the correct type using the as keyword:

    
    final extractedChildren = (listWidget[0] as Column).children.toList();
    
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      final List<Widget> listWidget = [
        Column(children: [
          Text('one'),
          Text('Two'),
          Text('Three'),
        ])
      ];
    
      @override
      Widget build(BuildContext context) {
        final extractedChildren = (listWidget[0] as Column).children.toList();
    
        return Scaffold(
          body: Column(
            children: [
              Text('Extracted widget:'),
              ...extractedChildren, // --> Display the extracted children here
            ],
          ),
        );
      }
    }