Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a custom class for decoration?

Tags:

flutter

dart

I want to use a background image for every page in my Flutter app. Therefore, I want to have a class that I can use to return a BoxDecoration to call it from every new page that I create. For the moment, I'm using a simple global function backgroundImage() that returns a BoxDecoration. Is there a way to have a custom class that I can directly pass to decoration: instead of calling a global function?

BoxDecoration backgroundImage() {
  return BoxDecoration(
    image: DecorationImage(
      image: AssetImage("images/background.png"),
      fit: BoxFit.cover,
    ),
  );
}

class HomeScreen extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: backgroundImage(),
        child: null /* add child content here */,
      ),
    );
  }
}
like image 564
Chris Avatar asked Oct 26 '25 01:10

Chris


1 Answers

It seems to me that what you want is a variable that you can import and re-use. Creating a new class in which you are only going be returning an instance of BoxDecoration with a few custom options is probably overkill. Why not create a separate file, import material, declare a variable with your customisation and use it? Like this example:

Custom decoration file to re-use:

import 'package:flutter/material.dart';

BoxDecoration baseBackgroundDecoration =
  BoxDecoration(
    image: DecorationImage(
      image: AssetImage("images/background.png"),
      fit: BoxFit.cover,
    ),
  );

Using it:

import 'custom_decorations.dart';

Using the variable:

Container(
  decoration: baseBackgroundDecoration,
),

There's nothing wrong with your original idea though. You wouldn't be using it as a global variable, just a file that you import when you need it, which contains a class with your custom decorations, like this:

import 'package:flutter/material.dart';

class CustomDecorations {
  BoxDecoration baseBackgroundDecoration(){
    return BoxDecoration(
      image: DecorationImage(
        image: AssetImage("images/background.png"),
        fit: BoxFit.cover,
      ),
    );
  }
}

Which you can then just use in one of these ways:

Container(
  decoration: CustomDecorations().baseBackgroundDecoration(),
),

Or:

// Declare it
CustomDecorations customDecorations = CustomDecorations();

...

// Use it
Container(
  decoration: customDecorations.baseBackgroundDecoration(),
),
like image 128
João Soares Avatar answered Oct 28 '25 17:10

João Soares



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!