0

Could anyone explain to me why dart formats the code in a way it does it? I have the dart plugin installed and have used the 'Dart: Use recommended settings'.

Future<void> addProduct(Product product) {
    return http
        .post(
      '$url.json',
      body: json.encode(
        {
          'title': product.title,
          'description': product.description,
          'imageUrl': product.imageUrl,
          'price': product.price,
          'isFavorite': product.isFavorite,
        },
      ),
    )
        .then((response) {
      var id = json.decode(response.body)['name'];
      var newProduct = Product(
        description: product.description,
        title: product.title,
        price: product.price,
        imageUrl: product.imageUrl,
        id: id,
      );
      _items.add(newProduct);
      notifyListeners();
    }).catchError((err) {});
  }
1
  • most likely the plugin uses dartfmt (i dont think the plugin formats your code internally)
    – pskink
    Commented Sep 4, 2019 at 8:08

1 Answer 1

2

As mentioned in the comments, the Dart extension just delegates formatting to dartfmt so the formatting is based on its conventions, including 2-spaces for indenting and 4-space indenting for line continuations.

dartfmt is an opinionated formatter so there's not much that can be controlled, though trailing commas will affect how it formats some code:

https://flutter.dev/docs/development/tools/formatting


(source: flutter.dev)


(source: flutter.dev)

4
  • Yes, the UI formatting works good. But this future, the way the then block is aligned feels wrong to me. Will it get formatted in a same way for everyone or there is something wrong with my setup? Commented Sep 7, 2019 at 21:40
  • Also, the fact that 'var id' is not indented relative to the '.then' also feels wrong. Commented Sep 7, 2019 at 21:43
  • If you put a trailing comma in }).catchError it'll partially fix that, but probably not to your liking. I would recommend extracting the functions into local variables to improve that. FWIW, I'm not the biggest fan of the formatting either, I do wish it was less opionated - but I'll take what's there over no automatic formatting :-) Commented Sep 8, 2019 at 13:25
  • The trailing comma did partially fixed the issue, thanks! Commented Sep 9, 2019 at 12:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.