本文介绍了下划线_ _表示什么意思? (_)在dart / flutter中调用函数时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读飞镖代码时,我经常看到一些仅带有下划线_参数调用的函数。它使我烦恼了一段时间,并且由于flutter改善了其分析消息,因此我有了一些线索...但是我觉得我不太了解这个概念:-(

When reading dart code I often see some functions called with just an underscore _ parameter. It's bugging me out for some time now and since flutter has improved its analysis messages I have some clues... but I feel like I don't really grasp this concept :-(

昨天我为测试编写了以下内容:

Yesterday I wrote the following for a test :

when(mockDevice.getLocalPath()).thenAnswer(() async => fileFolder);

并获得以下分析

添加下划线时效果很好。

When adding underscore it's working perfectly.

when(mockDevice.getLocalPath()).thenAnswer((_) async => fileFolder);

我遇到的最令人恐惧的例子来自@remi rousselet编写的提供程序包

The most frightenning example I meet come from provider package written by @remi rousselet

builder: (_, counter, __) => Translations(counter.value),

来自省der示例:

Widget build(BuildContext context) {
  return MultiProvider(
    providers: [
      ChangeNotifierProvider(builder: (_) => Counter()),
      ProxyProvider<Counter, Translations>(
        builder: (_, counter, __) => Translations(counter.value),
      ),
    ],
    child: Foo(),
  );
}

class Translations {
  const Translations(this._value);

  final int _value;

  String get title => 'You clicked $_value times';
}


推荐答案

下划线通常表示您不会在块内使用该参数,这只是编写代码的好方法,例如:

Underscore is normally an indication that you are not going to use that parameter inside the block it is just a good way to write code, for instance:

method(int useful, int useless) {
  // say I am only going to use 'useful' in this block 
}

上面的代码也可以写成:

Above code can also be written as:

method(int useful, int _) {
  // using '_' means I'm not going to use 2nd parameter in the block
}






现在回答您的问题:


Answer to your question now:

builder: (_, counter, __) => Translations(counter.value),

表示您有3个参数 _ 计数器 __ ,仅计数器是您正在使用的,因此第一个和第三个参数分别用 _ __ 表示。这是编写代码的更简洁的方法。

means you have 3 parameters _, counter and __, and only counter is what you are using, so 1st and 3rd parameters are denoted with _ and __. This is just cleaner way to write code.

这篇关于下划线_ _表示什么意思? (_)在dart / flutter中调用函数时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 12:14