How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

前端 未结 18 2144
再見小時候
再見小時候 2020-11-30 18:50

So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):



        
18条回答
  •  孤独总比滥情好
    2020-11-30 19:33

    I found out that an easy way to use conditional logic to build Flutter UI is to keep the logic outside of the UI. Here is a function to return two different colors:

    Color getColor(int selector) {
      if (selector % 2 == 0) {
        return Colors.blue;
      } else {
        return Colors.blueGrey;
      }
    }
    

    The function is used below to to set the background of the CircleAvatar.

    new ListView.builder(
      itemCount: users.length,
      itemBuilder: (BuildContext context, int index) {
        return new Column(
          children: [
            new ListTile(
              leading: new CircleAvatar(
                backgroundColor: getColor(index),
                child: new Text(users[index].name[0])
              ),
              title: new Text(users[index].login),
              subtitle: new Text(users[index].name),
            ),
            new Divider(height: 2.0),
          ],
        );
      },
    );
    

    Very neat as you can reuse your color selector function in several widgets.

提交回复
热议问题