'How to enable autoformating Flutter project in Android Studio?

For example, there is a sample flutter code. This code is not properly formatted.

import 'package:flutter/material.dart';

void main() => runApp(SampleApp());

class SampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Container(
            child: const Text('123'),), // this line isn't properly formatted 
        ),
      ),
    );
  }
}

I've heard that Android Studio is able to autoformat flutter code when a code saved in editor. In that case, certain conditions had to be respected, - all the commas should be present in code like it is in the above sample code. But I didn't find how to do that. So if it's true (i.e. if it's possible to do that) how to achive that?



Solution 1:[1]

Go to Settings -> Languages & Frameworks -> Flutter and check Format code on save.


You can also use Reformat code shortcut manually:

Windows/Linux: Ctrl + Alt + L

Mac: Command + Option + L

Solution 2:[2]

As @janstol said, there is a shortcut to auto reformat code. However, I had the same problem but I could not solve it because my command was not established, so I'll leave the route to get there in case someone needs it.

Open Setting > Preferences > Keymap and search for the one that says "Reformat code with 'dart format'". There you can customize it as needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 janstol
Solution 2 parkorian