Как избежать бесконечного утверждения высоты, создав Seperated ListView, состоящий из 3 контейнеров (левый, средний, правый раздел) - PullRequest
0 голосов
/ 18 апреля 2020

Я пытаюсь создать отдельный ListView, как показано на рисунке ниже. Каждый ListView-elemet должен состоять из 3 контейнеров (левая секция, средняя секция, правая секция). Есть кнопка приложения, которая создаст новый элемент Listview. введите описание изображения здесь

Я уже успешно создал просмотр списка и контейнеры, но получаю следующее исключение: ══════════════════════════════════════════════════════════════════════ ════════════════════════════════════════════════ Утверждение было выброшено во время executeLayout (): BoxConstraints принудительно устанавливает бесконечную высоту.

Вот мой код:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: ToDo()));

class ToDo extends StatelessWidget {
  // This widget is the root of your application.
  @override
  final List<String> list=[ 'x', 'y', 'y', 'x'];

  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
        title: Text('AppName',style: TextStyle(
            fontSize: 22.0,
            fontStyle: FontStyle.italic,
            fontWeight: FontWeight.w600,
            color: Colors.white
        ),

        ),leading: Icon(Icons.menu),  backgroundColor: Colors.redAccent,
        ),

        body: ListView.separated(
          separatorBuilder: (context, index)=> Divider(
            color: Colors.white,
          ),
          itemCount: eintraege.length,
          itemBuilder: (context, i){
        return new
        RowElement();
          },

    ),
    floatingActionButton: FloatingActionButton(
        onPressed: newEntry,
        child: Icon(Icons.add_circle_outline),
    )
    );

  }
}


class RowElementextends StatelessWidget {
  final leftSection = new Container();
  final middleSection = new Container();
  final rightSection = new Container();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(

          child: new Row(
            children: <Widget>[
              leftSection, middleSection, rightSection

            ],
          )
      ),
    );
  }
}
final leftSection = new Container(
  child: new CircleAvatar(
    //backgroundImage: new NetworkImage(url),
    backgroundColor: Colors.orangeAccent,
    radius: 24.0,
  ),
);

final middleSection = new Container(
  child: new Column(
    children: <Widget>[
      new Text("Name"),
      new Text("Hi whatsup?"),
    ],
  ),
);

final rightSection = new Container(

  child: new Column(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: <Widget>[
      new Text("9:50",
        style: new TextStyle(
            color: Colors.red,
            fontSize: 12.0),),
      new CircleAvatar(
        backgroundColor: Colors.orangeAccent,
        radius: 10.0,
        child: new Text("2",
          style: new TextStyle(color: Colors.white,
              fontSize: 12.0),),
      )
    ],
  ),
);

Ответы [ 2 ]

1 голос
/ 18 апреля 2020

Есть несколько проблем с вашим кодом.

Без объяснения всего, вот обзор вашего кода с некоторыми исправлениями:

Интересная часть - способ, которым вы можете построить свой раздел widgets

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: ToDo()));

class ToDo extends StatelessWidget {
  // This widget is the root of your application.
  @override
  final List<String> list = ['x', 'y', 'y', 'x'];

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            'AppName',
            style: TextStyle(fontSize: 22.0, fontStyle: FontStyle.italic, fontWeight: FontWeight.w600, color: Colors.white),
          ),
          leading: Icon(Icons.menu),
          backgroundColor: Colors.redAccent,
        ),
        body: ListView.separated(
          separatorBuilder: (context, index) => Divider(
            color: Colors.white,
          ),
          itemCount: 3,
          itemBuilder: (context, i) {
            return new RowElement();
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => print('object'),
          child: Icon(Icons.add_circle_outline),
        ));
  }
}

class RowElement extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var rightSection = Container(
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          new Text(
            "9:50",
            style: new TextStyle(color: Colors.red, fontSize: 12.0),
          ),
          new CircleAvatar(
            backgroundColor: Colors.orangeAccent,
            radius: 10.0,
            child: new Text(
              "2",
              style: new TextStyle(color: Colors.white, fontSize: 12.0),
            ),
          )
        ],
      ),
    );
    return new Container(
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          buildLeftSection(),    // A method returning Widget
          MiddleSectionWidget(), // A Widget class
          rightSection,          // A local variable
        ],
      ),
    );
  }

  Container buildLeftSection() {
    return Container(
      child: new CircleAvatar(
        backgroundColor: Colors.orangeAccent,
        radius: 24.0,
      ),
    );
  }
}

class MiddleSectionWidget extends StatelessWidget {
  const MiddleSectionWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: new Column(
        children: <Widget>[
          new Text("Name"),
          new Text("Hi whatsup?"),
        ],
      ),
    );
  }
}

Надеюсь, это поможет вам

0 голосов
/ 18 апреля 2020

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

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: ToDo()));

class ToDo extends StatelessWidget {
  // This widget is the root of your application.
  @override
  final List<String> list = ['x', 'y', 'y', 'x'];

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            'AppName',
            style: TextStyle(
                fontSize: 22.0,
                fontStyle: FontStyle.italic,
                fontWeight: FontWeight.w600,
                color: Colors.white),
          ),
          leading: Icon(Icons.menu),
          backgroundColor: Colors.redAccent,
        ),
        body: ListView.separated(
          separatorBuilder: (context, index) => Divider(
            color: Colors.white,
          ),
          itemCount: 10,//put your item count
          itemBuilder: (context, i) {
            return new RowElement();
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},//implement onPressed
          child: Icon(Icons.add_circle_outline),
        ));
  }
}

class RowElement extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        //left element
        Expanded(
          child: Container(
            child: new CircleAvatar(
              //backgroundImage: new NetworkImage(url),
              backgroundColor: Colors.orangeAccent,
              radius: 24.0,
            ),
          ),
        ),
        //middle element
        Expanded(
          child: Container(
            child: new Column(
              children: <Widget>[
                new Text("Name"),
                new Text("Hi whatsup?"),
              ],
            ),
          ),
        ),
        //right element
        Expanded(
          child: Container(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                new Text(
                  "9:50",
                  style: new TextStyle(color: Colors.red, fontSize: 12.0),
                ),
                new CircleAvatar(
                  backgroundColor: Colors.orangeAccent,
                  radius: 10.0,
                  child: new Text(
                    "2",
                    style: new TextStyle(color: Colors.white, fontSize: 12.0),
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...