Flutter: Creating dynamic Widgets in screen based on data source

It is very common we have to develop APP widgets which the elements have to be dynamically created based on a certain data set. And when programming with Flutter, it is not different.

Basically a Widget is composed of a list of another Widgets, which normally are pre-defined, as we can see in the example below:

body: Center(
  child:
Column(

    mainAxisAlignment:
MainAxisAlignment.center,
    children: <
Widget>[
     
Text(
       
'$name',
        style:
Theme.of(context).textTheme.headline4,
      ),
     
Text(
       
'$email',
        style:
Theme.of(context).textTheme.headline6,
      ),
     
Text(
       
'\n',
        style:
Theme.of(context).textTheme.headline6,
      ),

       ),

),

 

However, we can do that in a different manner. It is possible to dynamically produce a List<Widget> and then assign it to the children attribute.

Here we have a function which produces the widget list based on an array:

List<Widget> createElementsList(){
   
var contacts=["Chris Redfied","Albert Wesker", "Leon S. Kennedy","Jill Valentine","Rebecca Chambers"];
   
var widgets = new List.filled(contacts.length, Text(""), growable: false);
   
int i=0;
   
for (var contact in contacts) {
     
widgets[i]= Text(
       
contact+"\n",
        style:
Theme.of(context).textTheme.headline4,
      );
     
i++;
    }
   
return widgets;
  }

 

Then, we can call this function for children attribute assignment:

@override
Widget build(BuildContext context) {
 
return Scaffold(
    appBar:
AppBar(
      title:
Text(widget.title),
    ),
    body:
Center(
      child:
Column(
        mainAxisAlignment:
MainAxisAlignment.center,
        children: createElementsList(),
      ),
    ),
  );
}

 

You may find the complete source code here:

https://github.com/rafaelqg/code/blob/main/presenting_lists_dynamic_elements.dart

Take a look a hands-on presentation for this example:



Comments

Popular posts from this blog

Dart/Flutter: exception handling

Dart: implementing Object Oriented Programming (OOP)

Android – SearchView: Adding a Search component direct on your APP menu.