Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paint an Gradient on screen

Tags:

flutter

dart

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?

like image 903
Arash Avatar asked Mar 10 '26 21:03

Arash


1 Answers

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]
              ),
            ),
          ),
        ),
      ),
    );
  }
}
like image 190
Collin Jackson Avatar answered Mar 12 '26 15:03

Collin Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!