Оставьте равный интервал между элементами ряда во флаттере - PullRequest
0 голосов
/ 04 августа 2020

У меня тексты и переключатель в ряд, данные хорошие, но раскладка плохая. Я пробовал mainAxisAlignement.spaceAround или mainAxisAlignement.spaceBetween или mainAxisAlignement.spaceEvenly, но список элементов не выровнен зигзагообразно из-за размера текста. Я реализовал следующее введите описание изображения здесь

Виджет заголовка

return Container(
  margin: EdgeInsets.only(top: 20),
  width: MediaQuery.of(context).size.width,
  height: 50,
  decoration: BoxDecoration(
      border: Border(
          bottom: BorderSide(
        width: 5.0,
        color: Color.fromRGBO(232, 232, 232, 1),
      )),
      color: Colors.grey),
  child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Spacer(),
        Text("S.N"),
        Spacer(),
        Text("Food Name"),
        Spacer(),
        Text("Price"),
        Spacer(),
        Text("Qty"),
        Spacer(),
        Text("Action"),
        Spacer(),
      ]),
);

ListItems

return Container(
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
          border:
              Border(bottom: BorderSide(width: 5.0, color: Colors.grey[300])),
          color: Colors.white,
        ),
        child: Wrap(
          children: <Widget>[
            Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(child: Flexible(child: Text((i + 1).toString()))),
                Container(
                  child: Flexible(
                      child: Text(
                    removeAllHtmlTags(menuList[i].name),
                    softWrap: true,
                  )),
                ),
                Container(
                  child: Flexible(
                    child: Text(
                      removeAllHtmlTags(menuList[i].discountPrice.toString()),
                    ),
                  ),
                ),
                Container(
                  child: Flexible(
                    child: Text(
                      menuList[i].maxQty.toString(),
                    ),
                  ),
                ),
                Container(
                  width: 100,
                  child: menuList[i].status == 0
                      ? Text(
                          menuList[i].foodStatus,
                          style: TextStyle(color: Colors.red),
                        )
                      : YourListViewItem(
                          id: menuList[i].id,
                          index: menuList[i].status,
                        ),
                ),
              ],
            )
          ],
        ));

Виджет YourListViewItem

return ListTile(
      trailing: new Switch(
        value: isSwitched,
        activeColor: Colors.green,
        activeTrackColor: Colors.green,
        inactiveThumbColor: Colors.white,
        inactiveTrackColor: Colors.grey,
        onChanged: (value) {
          setState(() {
            if (isSwitched) {
              isSwitched = false;
              isSwitched = value;
              changeFoodStatus(widget.id);
            } else {
              isSwitched = true;
              isSwitched = value;
              changeFoodStatus(widget.id);
            }
          });
        },
      ),
    );

1 Ответ

1 голос
/ 04 августа 2020

Вместо этого вы можете использовать виджет Table, это избавит вас от стресса, связанного с вложением Columns и Rows, а также предоставлением фиксированных размеров вашим виджетам для соответствия экранам устройств.

Подробнее о Table виджет здесь: Класс таблицы

Я добавил демонстрацию, используя ваше дерево виджетов в качестве примера:

  1. Добавьте приведенный ниже фрагмент кода в качестве переменной чтобы дать пространство строк таблицы
// add this as a variable to gives the table rows spacing 
final TableRow rowSpacer = TableRow(children: [
    SizedBox(
      height: 15,
    ),
    SizedBox(
      height: 15,
    ),
    SizedBox(
      height: 15,
    ),
    SizedBox(
      height: 15,
    ),
    SizedBox(
      height: 15,
    ),
  ]);
Включите это в свое дерево виджетов, чтобы увидеть виджет Table в действии
// add this in your widget tree
 Table(
                // give each column in the table a fraction (to adapt to various screen sizes)
                columnWidths: {
                  0: FractionColumnWidth(.1),
                  1: FractionColumnWidth(.4),
                  2: FractionColumnWidth(.2),
                  3: FractionColumnWidth(.15),
                  4: FractionColumnWidth(.2)
                },
                children: [
                  // first table row
                  TableRow(
                    children: [
                      Text('S.N'),
                      Text('Food Name'),
                      Text('Price'),
                      Text('Qty'),
                      Text('Action'),
                    ],
                  ),
                  // space each row
                  rowSpacer,
                  // first table row
                  TableRow(
                    children: [
                      Text('1'),
                      Text('Burger'),
                      Text('180'),
                      Text('10'),
                      SizedBox(
                        height: 20,
                        child: Switch(
                          value: true,
                          onChanged: (val) {},
                        ),
                      ),
                    ],
                  ),

                  // space each row
                  rowSpacer,
                  // third table row
                  TableRow(
                    children: [
                      Text('2'),
                      Text('Chilli Momo'),
                      Text('140'),
                      Text('5'),
                      SizedBox(
                        height: 20,
                        child: Switch(
                          value: true,
                          onChanged: (val) {},
                        ),
                      ),
                    ],
                  ),

                  // .... // add other rows here
                ],
              ),

ВЫХОД:

img

...