Chris
Chris

Reputation: 3

Flutter Stack widget not sizing correctly when used in a ListView

I'm trying to build a List of Card's that contain a Stack widget, the Card + Stack Widget works just fine until I make it the child of a list view, and then the Stack no longer sizes automatically to its largest child. This is causing my view that should be aligned to the bottom right to only be right aligned instead since the bottom of the Stack isn't sized correctly.

I've tried wrapping all the children of the Stack with an Align, but that didn't help either. Positioned has the same results as Align.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Stack Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Scaffold(
        body: ListView(
          children: <Widget>[
            _buildCard(context),
            _buildCard(context),
            _buildCard(context),
            _buildCard(context),
            _buildCard(context),
            _buildCard(context),
          ],
        ),
      );

  Widget _buildCard(BuildContext context) => Card(
        child: Stack(
          children: <Widget>[
            SizedBox(
              height: 200,
              child: Container(
                color: Colors.black,
              ),
            ),
            Align(
              alignment: Alignment.bottomRight,
              child: SizedBox(
                height: 50,
                width: 50,
                child: Container(
                  color: Colors.red,
                ),
              ),
            ),
          ],
        ),
      );
}

What I'd expect to happen, is the Stack would size correctly around the black container allowing the red container to be positioned at the bottom right of the card.

Upvotes: 0

Views: 888

Answers (1)

hafidzaini
hafidzaini

Reputation: 76

try to set the alignment on the stack too

alignment: AlignmentDirectional.bottomEnd,

like this one

Widget _buildCard(BuildContext context) => Card(
    child: Stack(
      alignment: AlignmentDirectional.bottomEnd,
      children: <Widget>[
        SizedBox(
          height: 200,
          child: Container(
            color: Colors.black,
          ),
        ),
        Align(
          alignment: Alignment.bottomRight,
          child: SizedBox(
            height: 50,
            width: 50,
            child: Container(
              color: Colors.red,
            ),
          ),
        ),
      ],
    ),
  );

screenshot

Upvotes: 1

Related Questions