Create Flutter layout of rows and columns from map

176 Views Asked by At

How would it be possible to dynamically create rows and columns in flutter using a map element as the schematics?

If I had the following map:

   "rows":{
      0:{
        "cols":{
          0:{"text":"ABC"},
          1:{"text":"DEF"},
          2:{"text":"GHI"},
        },
      },
      1:{
        "cols":{
          0:{
            "rows":{
              0:{"text":"JKL"},
              1:{"text":"MNO"}
            },
          },
          1:{"text":"PQR"},
          2:{"text":"STU"},
        },
      },
    },

how would I make it into a series of flutter widgets:

Row(
  children:[
    Column(children: <Widget>[Text("ABC"),]),
    Column(children: <Widget>[Text("DEF"),]),
    Column(children: <Widget>[Text("GHI"),]),
 ),
Row(
  children:[
    Column(children: 
      Row(children: [
        <Widget>[Text("JKL"),
        <Widget>[Text("MNO"),
      ],
    ),
    Column(children: <Widget>[Text("PQR"),]),
    Column(children: <Widget>[Text("STU"),]),
  ]
)

I'd like it so that the number of levels deep is dynamic/nested widgets is infinite, that is, it doesn't iterate two levels down and then just stop.

To date, I've tried using for loops inside functions which refer to themselves, but I can't quite get it.

1

There are 1 best solutions below

0
Chris Pi On BEST ANSWER

You can try a Map.forEach() Recursion and validate for "cols" and "rows"something like this:

recursiveColsAndRows(Map blob) {
    blob.forEach((key, value) => {
    if(key == "cols") {
      // Do a recursion
      recursiveColsAndRows(value)
    }, 
    if(key == "rows") {
      // Do a recursion
      recursiveColsAndRows(value)
    },
      print(value)
  });
}

But with infinite nesting the way you think about, will bring you other big problems very soon, because you cannot display it infinitely without any scrolling features. That means after your third or fourth iteration, you will get an Overflowed Error because your Rows fall out of the Screen.

Infinite nesting the way you try to accomplish is not a good approach for displaying different data. Try to create proper widgets which fit your different types of needs.

PS: Are you maybe searching for a Table feature?