Как запретить строке занимать всю доступную ширину? - PullRequest
0 голосов
/ 14 июля 2020

У меня одна проблема с моим CustomChip:

Мне нужно обернуть карту, чтобы она соответствовала только содержимому.

Однако у меня есть второе требование: длинный текст должен выходить за пределы исчезают.

Когда я исправил вторую проблему, эта проблема начала возникать, когда я добавил Expanded, чтобы обернуть внутреннюю Row

Я не понимаю, почему внутренняя Row также кажется, расширяется, хотя его mainAxisSize уже установлено на min

введите описание изображения здесь

Вот код:

Экран:

import 'package:flutter/material.dart';
import 'package:app/common/custom_chip.dart';

class RowInsideExpanded extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(
              width: 1.0,
            ),
          ),
          width: 200.0,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildChip('short'),
              _buildChip('looooooooooooooooooooooongg'),
            ],
          ),
        ),
      ),
    );
  }

  _buildChip(String s) {
    return Row(
      children: [
        Container(
          color: Colors.red,
          width: 15,
          height: 15,
        ),
        Expanded(
          child: CustomChip(
            elevation: 0.0,
            trailing: Container(
              decoration: BoxDecoration(
                color: Colors.grey,
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.close),
            ),
            onTap: () {},
            height: 42.0,
            backgroundColor: Colors.black12,
            title: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Text(
                s,
                softWrap: false,
                overflow: TextOverflow.fade,
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 16.0),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

И CustomChip

import 'package:flutter/material.dart';
class CustomChip extends StatelessWidget {
  final Widget leading;
  final Widget trailing;
  final Widget title;
  final double height;
  final double elevation;
  final Color backgroundColor;
  final VoidCallback onTap;
  const CustomChip({
    Key key,
    this.leading,
    this.trailing,
    this.title,
    this.backgroundColor,
    this.height: 30.0,
    this.elevation = 2.0,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: elevation,
      color: backgroundColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(30.0),
      ),
      child: InkWell(
        onTap: onTap,
        child: Container(
          height: height,
          child: Padding(
            padding: const EdgeInsets.only(left: 5.0, right: 5.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                leading ?? Container(),
                SizedBox(
                  width: 5.0,
                ),
                Flexible(
                  child: title,
                  fit: FlexFit.loose,
                ),
                SizedBox(
                  width: 5.0,
                ),
                trailing ?? Container(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Ответы [ 2 ]

0 голосов
/ 14 июля 2020

Вместо Expanded просто замените его на Flexible, потому что Expanded наследует Flexible, но для свойства fit установите FlexFit.tight

Когда fit равно FlexFit.tight, ограничения блока для любого Flex виджета, являющегося потомком Flexible, получат такие же ограничения блока. Вот почему ваш Row все еще расширяется, даже если вы уже установили его MainAxisSize на min. Я изменил ваш код, чтобы распечатать ограничения окна с помощью виджета LayoutBuilder. Рассмотрим свой код с расширенным:

import 'package:flutter/material.dart';

class RowInsideExpanded extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(
              width: 1.0,
            ),
          ),
          width: 200.0,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildChip('short'),
              SizedBox(
                height: 5,
              ),
              _buildChip('looooooooooooooooooooooongg'),
            ],
          ),
        ),
      ),
    );
  }

  _buildChip(String s) {
    return Row(
      children: [
        Container(
          color: Colors.red,
          width: 15,
          height: 15,
        ),
        Expanded(
          child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
            print("outter $constraints");

            return Container(
              color: Colors.greenAccent,
              child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
                print("inner $constraints");

                return Row(
                  mainAxisSize: MainAxisSize.min, // this is ignored
                  children: <Widget>[
                    SizedBox(
                      width: 5.0,
                    ),
                    Flexible(
                      fit: FlexFit.loose,
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: Text(
                          s,
                          softWrap: false,
                          overflow: TextOverflow.fade,
                          style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 16.0),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 5.0,
                    ),
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.grey,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(Icons.close),
                    ),
                  ],
                );
              }),
            );
          }),
        ),
      ],
    );
  }
}

Он печатает

I / flutter (7075): outter BoxConstraints (w = 183.0, 0.0 <= h <= Infinity) I / flutter (7075): inner BoxConstraints (w = 183.0, 0.0 <= h <= Infinity) </p>

(Посмотрите на ширину в w, она должна быть 183.0 как для внешнего, так и для внутренний Row)

Теперь я изменил Expanded на Flexible и проверил журналы:

I/flutter ( 7075): outter BoxConstraints(0.0<=w<=183.0, 0.0<=h<=Infinity)
I/flutter ( 7075): inner BoxConstraints(0.0<=w<=183.0, 0.0<=h<=Infinity)

(посмотрите на ширину в w, она ограничена между ноль и 183.0 как для внешнего, так и для внутреннего Row)

Теперь ваш виджет исправлен:

0 голосов
/ 14 июля 2020

Найдите свойство «MainAxisSize» и установите значение «MainAxisSize.min»

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...