How to generate gradient background in Flutter
Flutter provides creative freedom to developers to create visually attractive applications by providing various UI features. Flutter is a single codebase framework that can be used across different platforms like Android and iOS. It has the pub package manager that offers a range of packages and plugins.
What is a gradient background?
A gradient background refers to a visually attractive effect that is created when two colors are gradually blended with each other, achieving various tones of the same shades. The transition from one color to another is smooth, creating a pleasing effect, as seen in the image below.
Let's code this feature and make a small application in Flutter.
Example code
In this example, we will create a simple gradient background generator that randomly generates background combinations and give code for them.
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(GradientBackgroundApp());
}
class GradientBackgroundApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: GradientBackgroundGenerator(),
);
}
}
class GradientBackgroundGenerator extends StatefulWidget {
@override
_GradientBackgroundGeneratorState createState() =>
_GradientBackgroundGeneratorState();
}
class _GradientBackgroundGeneratorState
extends State<GradientBackgroundGenerator> {
String gradientCode = '';
Color color1 = Colors.blue;
Color color2 = Colors.purple;
void generateGradient() {
final Random random = Random();
color1 = Color.fromRGBO(random.nextInt(256), random.nextInt(256),
random.nextInt(256), 1);
color2 = Color.fromRGBO(random.nextInt(256), random.nextInt(256),
random.nextInt(256), 1);
gradientCode = '''
background: linear-gradient(to bottom, ${color1.toString()}, ${color2.toString()});
''';
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Gradient Background Generator'),
centerTitle: true,
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [color1, color2],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Generated Gradient',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Container(
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 2),
),
child: Text(
gradientCode,
style: TextStyle(color: Colors.white),
),
),
SizedBox(height: 40),
ElevatedButton(
onPressed: generateGradient,
child: Text('Generate Random Gradient'),
),
],
),
),
),
);
}
}
Code explanation
Lines 1–5: Import the required packages and define the main by sending an instance of
GradientBackgroundAppto therunApp()method.Line 8: Define the
GradientBackgroundAppclass that extends theStatelessWidgetclass to access its methods and attributes.Lines 10–12: Override the
buildmethod and return aMaterialAppand set thehomeproperty toGradientBackgroundGenerator().
Lines 17–20: Define the
GradientBackgroundGenerator()class that extends theStatefulWidgetclass and create a_GradientBackgroundGeneratorState()instance.Lines 23–27: Define the
_GradientBackgroundGeneratorState()class that representsGradientBackgroundGeneratorstate and hold a string ofgradientCode, and two Color objects:color1andcolor2.
Lines 29–37: Create an
generateGradient()method that generates random color combinations, each stored incolor1andcolor2, respectively, and dynamically updates the string stored ingradientCode.Line 40: The
setState()method is called to set the changes made and preserve the newly assigned values to the attributes.Lines 44–45: Create the app UI in the
buildmethod that returns aScaffoldwidget containing the basic structure.Lines 46–48: Set the
appBarproperty to anAppBarwidget, which specifies the atitleand thebackgroundColor.Lines 50–55: Set the
bodytoContainerwidget with aLinearGradienttype and set the positions of the two colors in it.Lines 58–74: Create a
Centerwidget, and inside it, make aColumnwidget to align the content vertically and set the title, text styling, and font to get an interface as per requirements.Line 77: Create a box to display the generated gradient background code using
SizedBox()and pass the height as a parameter.Lines 78–80: Create
ElevatedButtonwidgets that trigger thegenerateGradientfunction when pressed and set the button text.
Code output
Press the Generate Random Gradient button and see the background dynamically change to a randomly created gradient color combination. The code for the generated color palette appears in the box so that it can be used for the required purposes.
Real-life application
There are a lot of real-life applications that require gradient backgrounds or even gradient background generation features to get customized backgrounds of choice. Let's look at a few scenarios where gradient backgrounds are useful.
Summary
Flutter is a user-friendly framework that helps developers to create cross-platform applications with an attractive user interface. We can create different widgets and assign functionalities to create a responsive application.
Note: Learn more about Flutter in the following Answers:
Free Resources