Adding a Gradient Background to Appbar on Flutter

MietieMn picture MietieMn · May 18, 2018 · Viewed 30.3k times · Source

I want to make the background of the AppBar a gradient, How can i do it.

Answer

Mans picture Mans · May 18, 2018

I don't believe you can pass a gradient to an AppBar as it expects a Color rather than a gradient.

You can, however, create your own widget that mimics an AppBar except by using a gradient. Take a look at this example that I've pieced together from the Planets-Flutter tutorial along with the code below it.

enter image description here

import "package:flutter/material.dart";

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(children : <Widget>[GradientAppBar("Custom Gradient App Bar"), Container()],);
  }
}


class GradientAppBar extends StatelessWidget {

  final String title;
  final double barHeight = 50.0;

  GradientAppBar(this.title);

  @override
  Widget build(BuildContext context) {
    final double statusbarHeight = MediaQuery
        .of(context)
        .padding
        .top;

    return new Container(
      padding: EdgeInsets.only(top: statusbarHeight),
      height: statusbarHeight + barHeight,
      child: Center(
        child: Text(
          title,
          style: TextStyle(fontSize: 20.0, color: Colors.white, fontWeight: FontWeight.bold),
        ),
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
            colors: [Colors.red, Colors.blue],
            begin: const FractionalOffset(0.0, 0.0),
            end: const FractionalOffset(0.5, 0.0),
            stops: [0.0, 1.0],
            tileMode: TileMode.clamp
        ),
      ),
    );
  }
}

Hope this helps. Let me know if you have any questions.