skip to Main Content

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

2

Answers


  1. 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
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. In your code:

    listWidget[0].childrens.toList(); //The "childrens" should be "children".
    
      @override
      Widget build(BuildContext context) {
    
       final item = listWidget[0];
    
        print("all childrens: ${item.children}");
        print("first: ${item.children[0]}");
        print("second: ${item.children[1]}");
        print("third: ${item.children[2]}");
    
        return Scaffold(
          body: Center(
            child: Text(item.children[0].toString()),
          ),
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search