CodeSadhu
CodeSadhu

Reputation: 375

Use class to pass parameters as list in Flutter

I'm working on a simple chatscreen UI in Flutter. There's a user-defined widget MessageBubble that accepts three parameters: sender (String), text (String), isMe (bool). Currently it is being passed static values one by one, like this:

List<MessageBubble> messages = [
    MessageBubble(
      sender: "Me",
      text: "Hi!",
      isMe: true,
    ),
    MessageBubble(
      sender: "Not Me",
      text: "Hey, hi!",
      isMe: false,
    ),
];

What I want to do instead, is I've created a class BubbleData like this:

class BubbleData {
    List <String> sender = ['Not Me', 'Not Me'];
    List <String> text = ['Hey Hi', "What's new?"];
    List <bool> isMe = [false, false];
}

Now the problem at hand lies that how do I iterate these listitems through the MessageBubble using a ListView builder?

Upvotes: 2

Views: 11482

Answers (3)

egonzal
egonzal

Reputation: 827

Following the answer of Akade. You can use it in a listView like this:

 class MyBubbleList extends StatelessWidget {

  final List<BubbleData> bubbles = [
   BubbleData(sender: 'Not Me', text: 'Hey Mi', isMe: false),
   BubbleData(sender: 'Not Me', text: 'What\'s new?', isMe: false)
];

  @override
  Widget build(BuildContext context) {

    //here the ListView part
    return ListView.builder(
      itemCount:bubbles.length,
      itemBuilder: (BuildContext context, int index) { 
             return Container(child:Text(bubbles[index].text));
      },);
  }
}

You can check more info in Flutter documentation. You will find very good video tutorial on how to use ListView. https://api.flutter.dev/flutter/widgets/ListView-class.html

Hope it helps

Upvotes: 1

Try
Try

Reputation: 3469

You can iterate like this:

BubbleData data = BubbleData();  //instantiating

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: ListView.builder(
      itemCount: data.sender.length,
      itemBuilder: (_, index) {
        return ListTile(
          title: Text(data.text[index]),         //iterating
          subtitle: Text(data.sender[index]),
        );
      },
    ),
  );
}

Upvotes: 0

Akade
Akade

Reputation: 41

Maybe a better approach would be to define your BubbleData as follows:

class BubbleData{
   String sender;
   String text;
   bool isMe;

   BubbleData({this.sender, this.text, this.isMe});
}

Then you create a list that can be iterated, with your data:

List<BubbleData> bubbles = [
   BubbleData(sender: 'Not Me', text: 'Hey Mi', isMe: false),
   BubbleData(sender: 'Not Me', text: 'What\'s new?', isMe: false)
];

Next step will be to map and convert to a MessageBubble's list:

List<MessageBubble> messages = bubbles.map((bubble) =>
   MessageBubble(
      sender: bubble.sender, 
      text: bubble.text, 
      isMe: bubble.isMe
   )
).toList();

Upvotes: 4

Related Questions