Search code examples
android-studiointellij-ideaflutterwidget

Shortcut to extract Flutter widget from UI layout


If I have a complex layout that I want to simplify, what is the shortcut in Android Studio (or IntelliJ) to extract the widget out into a method?

Example:

I want to extract the three main widgets in the Stack.

class BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/image.jpg'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Align(
          alignment: Alignment(-0.7, -0.7),
          child: Container(
            height: 300,
            child: RichText(
              text: TextSpan(
                text: 'My text',
                style: TextStyle(
                  color: Colors.white70,
                  fontSize: 30,
                ),
              ),
            ),
          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Text(
            'Some other text',
            style: TextStyle(
              color: Colors.white70,
              fontSize: 20.0,
              fontWeight: FontWeight.w900,
              letterSpacing: 5.0,
            ),
          ),
        ),
      ],
    );
  }
}

I could do it by hand but I'm looking for a shortcut.


Solution

  • I'm updating this answer for both Android Studio and VS Code

    Android Studio

    Method 1

    Shortcut keys:

    • Windows/Linux: Put your cursor on the widget name and press Ctrl+Alt+M to extract it as a method or Ctrl+Alt+W to extract it as a widget.
    • MacOS: Put your cursor on the widget name and press Option+Command+M to extract it as a method or Option+Command+W to extract it as a widget.

    You can also accomplish the same thing by right clicking the widget name and choosing Refactor > Extract from the context menu.

    Method 2

    You can also extract a widget into a method or new widget from the Flutter Outline menu.

    1. Click Flutter Outline on the top left side
    2. Select the widget in the outline
    3. Right click and choose Extract method... or Extract widget...
    4. Give it a name

    enter image description here

    Visual Studio Code

    Put your cursor on the widget name and press Command+. on a Mac or Ctrl+. on a PC. Then choose Method or Widget from the context menu.