【问题标题】:A map functions? don't understand this dart地图功能?不懂这个飞镖
【发布时间】:2022-11-15 12:44:59
【问题描述】:

我从飞镖酒吧的 google_fonts 看到了这个来源。看来我们有一个功能图? asMap() 有箭头函数吗?不明白这一点。

static Map<
      String,
      TextStyle Function({
    TextStyle? textStyle,
    Color? color,
    Color? backgroundColor,
    double? fontSize,
    FontWeight? fontWeight,
    FontStyle? fontStyle,
    double? letterSpacing,
    double? wordSpacing,
    TextBaseline? textBaseline,
    double? height,
    Locale? locale,
    Paint? foreground,
    Paint? background,
    List<ui.Shadow>? shadows,
    List<ui.FontFeature>? fontFeatures,
    TextDecoration? decoration,
    Color? decorationColor,
    TextDecorationStyle? decorationStyle,
    double? decorationThickness,
  })> asMap() => const {
        'ABeeZee': GoogleFonts.aBeeZee,
        'Abel': GoogleFonts.abel}

【问题讨论】:

  • 你不明白什么?

标签: dart


【解决方案1】:

您会在文件的最开头看到生成的代码:

// GENERATED CODE - DO NOT EDIT

// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

该函数定义为:

  • 姓名:asMap
  • 范围:顶级(因为它是静态方法)。
  • 返回类型:Map&lt;String, TextStyle Function({ ...args })&gt;

看来我们有一个功能图?

我们有一个返回字符串和闭包映射的函数。在 Dart 中,这完全没问题:

final Map<String, int Function(int, int)> operations = {
  'sum': (int a, int b) => a + b,
  'subtract': (int a, int b) => a - b,
  'multiply': (int a, int b) => a * b,
  'divide': (int a, int b) => a * b
};

operations['sum']!(30, 30); // 60
operations['subtract']!(30, 30); // 0
operations['multiply']!(30, 30); // 900
operations['divide']!(30, 30); // 1

一般来说,由于类型含义,这不是我们生手做的事情(难以维护,您可以看到它非常混乱 + 很容易忘记类型定义,因此很容易忘记所有智能感知功能)。这就是为什么这是通过代码生成来完成的。

在这种特殊情况下,我们正在生成一个地图,如下例所示:

class Arithmetic {
  static int sum(int a, int b) {
    return a + b;
  }
  static int subtract(int a, int b) {
    return a - b;
  }
  static int multiply(int a, int b) {
    return a * b;
  }
  static int divide(int a, int b) {
    return a * b;
  }
  static Map<String, int Function(int, int)> asMap() {
    const Map<String, int Function(int, int)> operationsAsMap = {
      'sum': sum,
      'subtract': subtract,
      'multiply': multiply,
      'divide': divide
    };
    return operationsAsMap;
  }
}

asMap() 有箭头功能吗?

不,asMap() 实现使用箭头函数,它是以下函数的别名:

// This is a shorthand...
static Map<...> asMap() => const { ... };

// For this:
static Map<...> asMap() {
  return const { ... };
}

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多