Столбец занимает больше места, чем требуется во Flutter - PullRequest
0 голосов
/ 21 июня 2020

Я пытаюсь создать представление страницы в столбце. Просмотр страницы будет содержать карточки. Я хочу, чтобы размер просмотра страницы был динамическим c для его содержимого, то есть карты, но я не могу этого добиться. Очевидно, столбец на карточке занимает больше места, чем требуется. Я проверил это с помощью инспектора флаттера и не могу понять, почему. Любая помощь будет оценена. Вот код.

import 'package:cricket_app/util/colors.dart';
import 'package:flutter/material.dart';
import 'package:page_view_indicators/circle_page_indicator.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  PageController _controller = PageController(
    initialPage: 0,
  );
  final _currentPageNotifier = ValueNotifier<int>(0);
  final double _cardHeight = 200.0;
  final double _teamIconSize = 50.0;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0,
        // flexibleSpace: Container(
        //   decoration: BoxDecoration(
        //       gradient: LinearGradient(
        //           begin: Alignment.topLeft,
        //           end: Alignment.bottomRight,
        //           colors: <Color>[Colors.red, Colors.blue])),
        // ),
        centerTitle: true,
        title: Text(
          "CRICKET APP",
        ),
      ),
      body: Column(
        children: <Widget>[
          Flexible(
            child: Column(
              children: <Widget>[
                Flexible(
                  child: PageView(
                    controller: _controller,
                    children: <Widget>[
                      _buildMatchCard(context, _teamIconSize),
                      _buildMatchCard(context, _teamIconSize),
                      _buildMatchCard(context, _teamIconSize),
                    ],
                    onPageChanged: (int index) {
                      _currentPageNotifier.value = index;
                    },
                  ),
                ),
                CirclePageIndicator(
                  dotColor: primaryColor,
                  selectedDotColor: accentColor,
                  itemCount: 3,
                  selectedSize: 10.0,
                  currentPageNotifier: _currentPageNotifier,
                )
              ],
            ),
          ),
          Expanded(
            child: Container(
              child: Center(
                  child: Text(
                "News Section",
                style: TextStyle(fontSize: 20.0),
              )),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildMatchCard(BuildContext context, double _teamIconSize) {
    return Card(
      margin: EdgeInsets.all(10.0),
      elevation: 2.0,
      color: darkGreyColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      child: Container(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 0),
              child: Text(
                "European Cricket Series, Stockholm, 11th Match",
                style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.black,
                    fontWeight: FontWeight.w500),
                textAlign: TextAlign.center,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(5.0),
              child: Text(
                "04:00 PM 22-Oct at Rajiv Ghandhi Stadium, Hyderabad",
                style: TextStyle(fontSize: 14.0),
                textAlign: TextAlign.center,
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          child: Image.asset(
                            'assets/icons/appIcon.jpg',
                            height: _teamIconSize,
                            width: _teamIconSize,
                          ),
                        ),
                        SizedBox(
                          height: 10.0,
                        ),
                        Text(
                          "WI",
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 18.0,
                              fontWeight: FontWeight.w500),
                        )
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              "250/8",
                              style: TextStyle(
                                  fontSize: 24.0, color: Colors.black),
                            ),
                            Text("50 Over")
                          ],
                        ),
                      ),
                    )
                  ],
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "Live",
                      style: TextStyle(
                          fontSize: 16.0,
                          color: Colors.red,
                          fontWeight: FontWeight.w500),
                    ),
                    Container(
                      width: 20.0,
                      height: 20.0,
                      margin: EdgeInsets.only(top: 5.0, bottom: 5.0),
                      decoration: new BoxDecoration(
                        color: accentColor,
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                          child: Text(
                        "VS",
                        style: TextStyle(
                            fontSize: 12.0, fontWeight: FontWeight.w500),
                      )),
                    ),
                    Row(
                      children: <Widget>[
                        Container(
                          padding: EdgeInsets.fromLTRB(10.0, 3.0, 10.0, 3.0),
                          color: Colors.red,
                          child: Text("56"),
                        ),
                        SizedBox(
                          width: 5.0,
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(10.0, 3.0, 10.0, 3.0),
                          color: Colors.red,
                          child: Text("56"),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.all(5.0),
                      child: Text("Fav - IND"),
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              "250/8",
                              style: TextStyle(
                                  fontSize: 24.0, color: Colors.black),
                            ),
                            Text("50 Over")
                          ],
                        ),
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image.asset(
                          'assets/icons/appIcon.jpg',
                          height: _teamIconSize,
                          width: _teamIconSize,
                        ),
                        SizedBox(
                          height: 10.0,
                        ),
                        Text(
                          "WI",
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 18.0,
                              fontWeight: FontWeight.w500),
                        )
                      ],
                    ),
                  ],
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.all(4.0),
              child: Text(
                "INDIA needs 126 runs in 155 balls to win",
                style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
                textAlign: TextAlign.center,
              ),
            )
          ],
        ),
      ),
    );
  }
}

Ответы [ 2 ]

1 голос
/ 21 июня 2020

Вы должны установить соответствующий mainAxisSize в соответствии с официальной документацией

Высота столбца определяется свойством mainAxisSize. Если свойство mainAxisSize - MainAxisSize.max, то высота столбца - это максимальная высота входящих ограничений. Если свойство mainAxisSize - MainAxisSize.min, то высота столбца - это сумма высот дочерних элементов (с учетом входящих ограничений

...
child: Column(
          mainAxisSize: MainAxisSize.  //MIN or MAX
          children: <Widget>[
            Padding(
...
0 голосов
/ 23 июня 2020

Проблема здесь в PageView. PageView постарается получить максимальную высоту. Таким образом, вы не можете использовать его, не указав заранее заданную высоту. Либо вы можете определить высоту своей карточки задолго до создания pageView, либо указать жестко заданную высоту, что может быть плохо, учитывая отзывчивый характер приложения. будет пытаться захватить всю высоту экрана, если это возможно. Итак, вот способ решения вашей проблемы. Вы можете изменить его в соответствии с вашими требованиями.

Решение

Оберните ваш просмотр страницы внутри IndexedStack и виджета контейнера и задайте высоту, которая определяет размер вашего просмотра страницы.

IndexedStack(
            children: [
              Container(
                height: 280,
                child: PageView( . . . ) ) ] )

Так что проблема не в методе buildCard, а в просмотр страницы занимает высоту независимо от размера вашей карты.

import 'package:cricket_app/util/colors.dart';
import 'package:flutter/material.dart';
import 'package:page_view_indicators/circle_page_indicator.dart';

class App extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<App> {
  PageController _controller = PageController(
    initialPage: 0,
  );
  final _currentPageNotifier = ValueNotifier<int>(0);
  final double _cardHeight = 200.0;
  final double _teamIconSize = 50.0;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white70,
        elevation: 0,
        // flexibleSpace: Container(
        //   decoration: BoxDecoration(
        //       gradient: LinearGradient(
        //           begin: Alignment.topLeft,
        //           end: Alignment.bottomRight,
        //           colors: <Color>[Colors.red, Colors.blue])),
        // ),
        centerTitle: true,
        title: Text(
          "CRICKET APP",
        ),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          IndexedStack(
            children: [
              Container(
                height: 280,
                child: PageView(
                  controller: _controller,
                  children: <Widget>[
                    _buildMatchCard(context, _teamIconSize),
                    _buildMatchCard(context, _teamIconSize),
                    _buildMatchCard(context, _teamIconSize),
                  ],
                  onPageChanged: (int index) {
                    _currentPageNotifier.value = index;
                  },
                ),
              )
            ],
          ),
          Expanded(
            child: Container(
              child: Center(
                  child: Text(
                "News Section",
                style: TextStyle(fontSize: 20.0),
              )),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildMatchCard(BuildContext context, double _teamIconSize) {
    return Card(
      margin: EdgeInsets.all(10.0),
      elevation: 2.0,
      color: Colors.cyan,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
//        child: Text("das"),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 0),
            child: Text(
              "European Cricket Series, Stockholm, 11th Match",
              style: TextStyle(
                  fontSize: 18.0,
                  color: Colors.black,
                  fontWeight: FontWeight.w500),
              textAlign: TextAlign.center,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Text(
              "04:00 PM 22-Oct at Rajiv Ghandhi Stadium, Hyderabad",
              style: TextStyle(fontSize: 14.0),
              textAlign: TextAlign.center,
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        child: Image.asset(
                          'assets/images/img my hello bye.png',
                          height: _teamIconSize,
                          width: _teamIconSize,
                        ),
                      ),
                      SizedBox(
                        height: 10.0,
                      ),
                      Text(
                        "WI",
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 18.0,
                            fontWeight: FontWeight.w500),
                      )
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "250/8",
                          style: TextStyle(fontSize: 24.0, color: Colors.black),
                        ),
                        Text("50 Over")
                      ],
                    ),
                  )
                ],
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "Live",
                    style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.red,
                        fontWeight: FontWeight.w500),
                  ),
                  Container(
                    width: 20.0,
                    height: 20.0,
                    margin: EdgeInsets.only(top: 5.0, bottom: 5.0),
                    decoration: new BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                        child: Text(
                      "VS",
                      style: TextStyle(
                          fontSize: 12.0, fontWeight: FontWeight.w500),
                    )),
                  ),
                  Row(
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.fromLTRB(10.0, 3.0, 10.0, 3.0),
                        color: Colors.red,
                        child: Text("56"),
                      ),
                      SizedBox(
                        width: 5.0,
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(10.0, 3.0, 10.0, 3.0),
                        color: Colors.red,
                        child: Text("56"),
                      )
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.all(5.0),
                    child: Text("Fav - IND"),
                  )
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "250/8",
                          style: TextStyle(fontSize: 24.0, color: Colors.black),
                        ),
                        Text("50 Over")
                      ],
                    ),
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Image.asset(
                        'assets/images/img my hello bye.png',
                        height: _teamIconSize,
                        width: _teamIconSize,
                      ),
                      SizedBox(
                        height: 10.0,
                      ),
                      Text(
                        "WI",
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 18.0,
                            fontWeight: FontWeight.w500),
                      )
                    ],
                  ),
                ],
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.all(4.0),
            child: Text(
              "INDIA needs 126 runs in 155 balls to win",
              style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
              textAlign: TextAlign.center,
            ),
          )
        ],
      ),
    );
  }
}

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

...