【问题标题】:Dart formatting issue [VSCODE]Dart 格式问题 [VSCODE]
【发布时间】:2020-01-07 02:10:42
【问题描述】:

谁能向我解释为什么 dart 以它的方式格式化代码? 我安装了 dart 插件并使用了“Dart:使用推荐的设置”。

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) {});
  }

【问题讨论】:

  • 插件很可能使用dartfmt(我认为插件不会在内部格式化您的代码)

标签: flutter dart visual-studio-code formatting


【解决方案1】:

如 cmets 中所述,Dart 扩展只是将格式化委托给 dartfmt,因此格式化基于其约定,包括用于缩进的 2 个空格和用于续行的 4 个空格缩进。

dartfmt 是一个固执己见的格式化程序,所以没有什么可以控制的,尽管尾随逗号会影响它格式化某些代码的方式:

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

【讨论】:

  • 是的,UI 格式效果很好。但是这个未来,then 块的对齐方式对我来说感觉不对。它会以相同的方式为每个人格式化还是我的设置有问题?
  • 另外,'var id' 相对于 '.then' 没有缩进的事实也让人感觉不对。
  • 如果你在}).catchError 中添加一个逗号,它会部分解决这个问题,但可能不是你喜欢的。我建议将函数提取到局部变量中以改进它。 FWIW,我也不是格式化的最大粉丝,我希望它不那么受欢迎 - 但我会接受没有自动格式化的内容:-)
  • 结尾的逗号确实部分解决了问题,谢谢!
猜你喜欢
  • 2020-11-20
  • 2018-12-26
  • 1970-01-01
  • 2021-06-18
  • 2019-07-01
  • 2021-04-01
  • 2022-12-28
  • 2021-10-05
  • 2018-11-25
相关资源
最近更新 更多