Arash
Arash

Reputation: 12415

Paint an Gradient on screen

To implement a color picker, I want to draw a rectangle with a gradient of colors inside. I tried to use a container with a DecoratedBox but it didn't quite work, as I had to give it a width, and I wanted it to fill its parent. What is the best way to draw a Gradient in flutter?

Upvotes: 3

Views: 2788

Answers (1)

Collin Jackson
Collin Jackson

Reputation: 116708

It sounds like you already know how to draw a gradient and your question is more about how to make a DecoratedBox as big as possible.

If your DecoratedBox appears in a Column or Row, consider wrapping it in an Expanded and setting the crossAxisAlignment to CrossAxisAlignment.stretch.

If your DecoratedBox is a child of a widget that doesn't provide a size to its child (e.g. Center), try wrapping it in a ConstrainedBox with a constraints of new BoxConstraints.expand(). Here's an example:

screenshot

import 'package:flutter/material.dart';

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

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Gradient Example'),
      ),
      body: new Center(
        child: new ConstrainedBox(
          constraints: new BoxConstraints.expand(),
          child: new DecoratedBox(
            decoration: new BoxDecoration(
              gradient: new LinearGradient(
                colors: <Color>[Colors.red, Colors.blue]
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Upvotes: 2

Related Questions