ref – https://medium.com/flutter-community/using-extension-methods-in-flutter-612b8db532ae
We extend all classes that derives from Widget with the ability of having:
1) a black colored border of width 5
2) Background color of red
3) circular border radius of 8
4) padding and margin of 16
We do so by returning a Container where we specify the decoration property.
We assign it to an instance of BoxDecoration.
From there, we simply fill in the properties of BoxDecoration.
this refers to the original Widget we are applying these attributes to. So in our case it is
AutoSizeText. When we call addContainer extension, it would return a Container where its child references
the AutoSizeText. Thus wrapping our AutoSizeText with a Container.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import 'dart:developer'; import 'package:flutter/material.dart'; extension ExtendedText on Widget { addContainer() { return Container( decoration: BoxDecoration( color: Colors.red[500], border: Border.all( color: Colors.black, width: 5, ), borderRadius: BorderRadius.all(Radius.circular(8)), ), padding: const EdgeInsets.all(16), margin: const EdgeInsets.all(16), child: this, ); } } |
Then, just use like so:
1 2 3 |
AutoSizeText("Hi, I'm a Web Developer </>", style: GoogleFonts.montserrat(fontSize: 40), maxLines: 2) .addContainer(), |