skip to Main Content

I have a custom table widget, that has a property of type List holding items with certain properties.

final List<Item> items;

Where each of the items can have properties like "name", "street", "number" etc. This list is passed to the constructor.

Since i have now another class that should use the same widget again, i want to decouple it from the "Item" class itself. Instead i think its a good idea to define the properties that should be displayed in the table itself as a contructor argument instead binding it to a certain class, which isn’t really flexible

The question is, how can i pass a list of "named" properties to the constructor, without using a class/data container?

so i need something like

List<[name, street, number]>

So i wanna force the caller to input a list, where each of the described property in the list has a value. So i can iterate over this and create rows

But this seems not to exist. Is there a way to do this in flutter? Or even a more flexible way where the caller can pass a variable count of data to display?

2

Answers


  1. You can use dart 3.0 feature RECORDS:

    void main() {
      List< ( {String name, String street, int number} )  > items=[];
      var x=(name: 'Joe', street: 'street A', number: 111);
      print(x.name); //Joe
      items.add(x);
      items.add((name: 'Anna', street: 'street B', number: 222));
      print(items); //[(name: Joe, number: 111, street: street A), (name: Anna, number: 222, street: street B)]
      var y=items[0];
      print(y);//(name: Joe, number: 111, street: street A)
      print(y.street);//street A
    }
    
    Login or Signup to reply.
  2. You can use Maps:

    List <Map<String, dynamic>> items = [
    { 'name': 'James', 
     'street': 'example',
     'number': 1 },
    { 'name': 'Mark', 
     'street': 'example2',
     'number': 2 },
    ];
    

    Then call a variable like this:

    print(items[index]['name']);
    

    In my example, name, street and number are all strings. If you want to call different types, you just need to redefine your map to Map<dynamic, dynamic>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search