flutter / website

Flutter documentation web site
https://docs.flutter.dev
Other
2.82k stars 3.22k forks source link

Consider rewriting `Create lists with different types of items` to `sealed` classes with pattern matching. #11335

Open vasilich6107 opened 6 hours ago

vasilich6107 commented 6 hours ago

What information needs to be added?

https://docs.flutter.dev/cookbook/lists/mixed-list is a bit outdated

In addition the approach is probably not the best cause it ties together the data class and build method which is less reusable.

Where should this new content appear?

Consider

sealed class ListItem {
}

class HeadingItem extends ListItem {
  final String heading;

  HeadingItem(this.heading);
}

class MessageItem extends ListItem {
  final String sender;
  final String body;

  MessageItem(this.sender, this.body);
}
class ListItemTitle extends StatelessWidget {}
class ListItemSubTitle extends StatelessWidget {}

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    final item = items[index];

   return switch(item) {
      final HeadingItem _ => ListTile(
          title: ListItemTitle(item.heading),
        ),
      final MessageItem _ => ListTile(
          title: ListItemTitle(item.sender),
          subtitle: ListItemSubtitle(item.body),
        )
   }
  },
)

I would like to fix this problem.

vasilich6107 commented 6 hours ago

If it is look ok for you I can make a PR with fixes