Kdon
Kdon

Reputation: 1225

How to split a container up into various colors in Flutter?

I want to split a container into multiple colors at various different points (which can change dynamically).

I get this effect almost by using LinearGradient - however, I want sharp borders (e.g. no blending of colors when they change). How can I achieve this?

enter image description here

        final size = MediaQuery.of(context).size;
        var colors = [Colors.red, Colors.blue, Colors.green, Colors.orange];
        var stops = [0.0, 0.15, 0.60, 1.00];

        return SizedBox(
          child: Container(
            width: size.width,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: colors,
                stops: stops,
              ),
            ),
          ),
        );

Upvotes: 0

Views: 696

Answers (1)

Valentin Vignal
Valentin Vignal

Reputation: 8222

If you just want to display your colors with no gradient, here is a way:

class MyWidget extends StatelessWidget {
  const MyWidget();

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          flex: 7,
          child: Container(
            color: Colors.red,
          ),
        ),
        Expanded(
          flex: 31,
          child: Container(
            color: Colors.blue,
          ),
        ),
        Expanded(
          flex: 42,
          child: Container(
            color: Colors.green,
          ),
        ),
        Expanded(
          flex: 20,
          child: Container(
            color: Colors.orange,
          ),
        ),
      ],
    );
  }
}

The result:

enter image description here

You can make it more dynamic by creating the row from a list. Changing the flex values with change the size of the corresponding color.

Upvotes: 2

Related Questions