31

I am able to draw a semi circle using the following example: Flutter how to draw semicircle (half circle)

However, the Paint object only seems to accept a Color (using Paint.color). I would like to add a RadialGradient or LinearGradient as the Color. Is that possible?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
user2511882
  • 9,022
  • 10
  • 51
  • 59
  • Does this answer your question? [Arc gradients in Flutter?](https://stackoverflow.com/questions/50225628/arc-gradients-in-flutter) – TheMisir Feb 01 '20 at 18:04
  • I did see that. I am trying to see if we can add a ```LinearGradient``` using the link shared in the question. – user2511882 Feb 01 '20 at 18:10

1 Answers1

78

Yes! This is totally possible using Paint.shader.
You can either create a gradient shader directly using dart:ui or convert a Flutter gradient to a shader using Gradient.createShader.

dart:ui gradient

import 'dart:ui' as ui;

// In your paint method
final paint = Paint()
  ..shader = ui.Gradient.linear(
    startOffset,
    endOffset,
    [
      color1,
      color2,
    ],
  );

A real world example can be seen here.

Flutter painting gradient

import 'package:flutter/painting.dart';

// In your paint method
final paint = Paint()
  ..shader = RadialGradient(
    colors: [
      color1,
      color2,
    ],
  ).createShader(Rect.fromCircle(
    center: offset,
    radius: radius,
  ));

An example of this can be found here.


These two are effectively the same. The Flutter painting version simply converts it to a dart:ui gradient (shader) when you call createShader. The reason it exists is that the painting version is better suited for prebuilt widgets like Container.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402