Skip to main content

Compositions

composition means building complex widgets by combining simpler widgets.

  • Use Composition instead of Inheritance to extend Widgets which are already defined or which already extend a StatelessWidget.

Must know for composition

Extract Widget

  • in Android Studio put your cursor on WidgetName, right-click and choose Refactor ▸ Extract ▸ Method from the context menu.
  • in VS Code put your cursor on WidgetName, CTRL+.or [right-click and choose Refactor] ▸ choose Extract ▸ Method from the menu.
caution

Error: Reference to an enclosing class method cannot be extracted.

Solution: If you want to use "Extract Widget" only then simply wrap that widget in a Container and then use "Extract Widget" on that widget. If that doesn't work, comment out setState() function inside the widget and try again.


Extract Method OR Private Helper MKethod

This is known as Private Helper Method

  • in Android Studio: put your cursor on WidgetName, right-click and choose Refactor ▸ Extract ▸ Method from the context menu.
  • in VS Code: put your cursor on WidgetName, CTRL+.or [right-click and choose Refactor] ▸ choose Extract ▸ Method from the menu.
info

when given widget is to be used again and again with same components but only different icons or text then use : Composition in the form of creating a Method of return type of that WidgetName with Named Parameters and can call that method from anywhere we want with different parameter values

name that method private variable i.e. _nameYouGive

caution

when Extract Method then must use static in that funtion declaration or else when that function is called we get error : The instance member '_buildButtonColumn' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

Refer: implicit_this_reference_in_initializer

 final Widget buttonRow = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
_buildButtonColumn(Colors.red, Icons.abc, 'Alphabet'), /// The instance member '_buildButtonColumn' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
_buildButtonColumn(Colors.red, Icons.star, 'Star'), /// The instance member '_buildButtonColumn' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
_buildButtonColumn(Colors.red, Icons.add, 'Add'), /// The instance member '_buildButtonColumn' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
],
),
);

static Column _buildButtonColumn(Color color, IconData icon, String label) => Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color),
Text(
label,
style: TextStyle(
fontSize: 12, fontWeight: FontWeight.w400, color: color),
)
],
);