How to use well formatted arrow functions in Dart?

Issue

Working on a flutter/dart project I’m currently almost always thinking about a way to decrease my code size, considering that one of the things would be using arrow functions to avoid the brackets.

However I can’t find a way to keep them in a nice look, e.g. if I use this code:

@widget
Widget poscompExams() => StoreConnector<AppState, ViewModel>(
    converter: ViewModel.fromStore,
    builder: (BuildContext context, ViewModel vm) => Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: vm.poscomp.exams.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Test'),
                    subtitle: const Text('Inserção das provas em andamento'),
                    leading: const Icon(Icons.computer),
                    onTap: () => {}
                  );
                },
              ),
            ),
          ],
      );
    },
  );

It would be much nicer if the look was like this:

@widget
Widget poscompExams() => 
  StoreConnector<AppState, ViewModel>(
    converter: ViewModel.fromStore,
    builder: (BuildContext context, ViewModel vm) => 
      Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: vm.poscomp.exams.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Test'),
                    subtitle: const Text('Inserção das provas em andamento'),
                    leading: const Icon(Icons.computer),
                    onTap: () => {}
                  );
                },
              ),
            ),
          ],
      );
    },
  );

I research about some way and find the dart_style, but it seems to follow the general same pattern to format.

It would be nice something like prettier on Javascript, with flag options.

Solution

Generally, if you get past six or seven levels of indentation, it’s time to refactor. This will make it easier for you to override parts of it for variations, and easier for people reading and maintaining your code to understand your intent.

In your specific code, I’d take the ListView.builder out as a separate method in your class. There are IDE operations to help with that kind of refactor.

Also, in your code, () => {} is a function returning an empty map. You should fix that to just () {}.

Answered By – Randal Schwartz

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *