Как ограничить ListTile в иерархии виджетов - PullRequest
1 голос
/ 03 августа 2020

Как я могу заставить ListTile работать внутри этой иерархии виджетов:

            SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Column(
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Radio(
                        value: 1,
                        groupValue: 1,
                        onChanged: (sel) {},
                      ),
                      GestureDetector(
                        child: Row(
                          children: <Widget>[
                            //Text('Title'), -- This is OK, but ListTile fails
                            ListTile(
                              title: Text('Title'),
                              subtitle: Text('Subtitle'),
                            ),
                          ],
                        ),
                        onTap: () {},
                      ),
                    ],
                  ),
                ],
              ),
            ),

Пожалуйста, поймите, что я не полностью контролирую иерархию виджетов - структура создает SingleChildScrollView, Radio, GestureDetector и др. c. Я просто пытаюсь предоставить виджет дочерний для опции. (Я воспроизвел иерархию в упрощенной форме для отладки и экспериментов.)

Я получаю исключение:

flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: BoxConstraints forces an infinite width.
flutter: These invalid constraints were provided to RenderParagraph's layout() function by the following
flutter: function, which probably computed the invalid constraints in question:
flutter:   _RenderListTile._layoutBox (package:flutter/src/material/list_tile.dart:1318:9)
flutter: The offending constraints were:
flutter:   BoxConstraints(w=Infinity, 0.0<=h<=Infinity)

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

Обратите внимание, что если я заменю ListTile простым Text виджетом, он будет отображаться нормально.

Ответы [ 2 ]

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

Вы можете обернуть ListTile в Container или ConstrainedBox и установить его maxWidth:

ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width - 50,
      ),
      child: ListTile(
        title: Text('Title'),
        subtitle: Text('Subtitle'),
        trailing: Text('Trailing'),
      ),
    ),
0 голосов
/ 04 августа 2020

Вы можете скопировать и вставить полный код ниже
Вы можете использовать IntrinsicWidth wrap Row и Expanded wrap ListTile, и у вас может быть более одного Expaned ListTile

GestureDetector(
                  child: IntrinsicWidth(
                    child: Row(
                      children: <Widget>[
                        //Text('Title'), -- This is OK, but ListTile fails
                        Expanded(
                          child: ListTile(
                            title: Text('Title'),
                            subtitle: Text('Subtitle'),
                          ),
                        ),
                      ],
                    ),
                  ),

рабочая демонстрация

enter image description here

full code

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Radio(
                  value: 1,
                  groupValue: 1,
                  onChanged: (sel) {},
                ),
                GestureDetector(
                  child: IntrinsicWidth(
                    child: Row(
                      children: [
                        //Text('Title'), -- This is OK, but ListTile fails
                        Expanded(
                          child: ListTile(
                            isThreeLine: true,
                            title: Text('Title'),
                            subtitle: Text('this is long text this is long text this is long text \n'* 10),
                          ),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {},
                ),
              ],
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

full code 2 relayout

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';

    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }

    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);

      final String title;

      @override
      _MyHomePageState createState() => _MyHomePageState();
    }

    class _MyHomePageState extends State {
      int _counter = 0;

      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              children: [
                Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      flex: 1,
                      child: Radio(
                        value: 1,
                        groupValue: 1,
                        onChanged: (sel) {},
                      ),
                    ),
                    Expanded(
                      flex: 5,
                      child: GestureDetector(
                        child: LayoutBuilder(
                          builder:(context, constraints) {
                            print(constraints.maxWidth);
                            print(constraints.minWidth);
                            return ConstrainedBox(
                              constraints: BoxConstraints(                            
                                  maxWidth: constraints.maxWidth),
                              child: ListTile(
                                //isThreeLine: true,
                                title: Text('Title'),
                                subtitle: Text(
                                  'Textlargeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                  style: TextStyle(
                                    fontSize: 13.0,
                                    fontFamily: 'Roboto',
                                    color: Color(0xFF212121),
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            );
                          }
                        ),
                        onTap: () {},
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }

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

...