Nerdy Bunz
Nerdy Bunz

Reputation: 7427

How to have a dynamically sized CustomPainter in Flutter?

Consider the following code from the Flutter docs:

CustomPaint(
  painter: Sky(),
  child: const Center(
    child: Text(
      'Once upon a time...',
      style: TextStyle(
        fontSize: 40.0,
        fontWeight: FontWeight.w900,
        color: Color(0xFFFFFFFF),
      ),
    ),
  ),
)

I don't want a text widget.

I don't want the CustomPaint widget to be obscured by a child widget.

Also I want the CustomPaint widget to fill whatever space is available to it.

I presume the solution is to replace the Text widget with a BLANK widget like Expanded.

But, I've tried the Expanded, Container, Spacer, and Space widgets in various combinations but always either get an error or a zero size.

Thanks!

Upvotes: 2

Views: 1602

Answers (2)

Diwyansh
Diwyansh

Reputation: 3514

You can get height and width of the screen by using MediaQuery and use them

Note : The people who are negative marking I respect their efforts and want to thank them but along with that I would like to request them that kindly read the entire post with patience that the question has been updated after date of answer as it's already negative I'm not gonna update it but hoping some humour with those kinds of people. thanks

final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    return CustomPaint(
      size: Size(width,height),
      painter: Sky(),
      child: const Center(
        child: Text(
          'Once upon a time...',
          style: TextStyle(
            fontSize: 40.0,
            fontWeight: FontWeight.w900,
            color: Color(0xFFFFFFFF),
          ),
        ),
      ),
    );

Upvotes: -3

Nerdy Bunz
Nerdy Bunz

Reputation: 7427

Here how you do it:

Expanded(
  child: CustomPaint(
    painter: MyCustomPainter(),
    size: Size.infinite,

  ),
),

Upvotes: 1

Related Questions