跳到正文
教程首页
DartCH 01ch01_dart_basics

ch01-dart-basics

Dart 起步:值与变量、函数、基础类型、const/final。完整工程共 6 个文件,其中 6 个文本源文件可在下面在线阅读。

6

在线文本文件

824

源码行数

dart / yaml / text

语言

11 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

darttextyaml

6 text files · 824 lines

dartbin/ch01_dart_basics.dart
// 第 1 章可运行入口:`dart run` 依次打印各小节的演示结果。
import 'package:ch01_dart_basics/basics.dart';

void main() {
  print('--- 1. 数字 ---');
  print('int 溢出回绕: ${intOverflow()}');
  print('7 ~/ 2 = ${truncatingDivision(7, 2)}, 7 / 2 = ${doubleDivision(7, 2)}');
  print('-7 % 3 = ${moduloFollowsDivisor(-7, 3)} (C/Go 给 -1)');
  print('7 % -3 = ${moduloFollowsDivisor(7, -3)} · 7.remainder(-3) = ${cStyleRemainder(7, -3)}');
  print('0.1 + 0.2 == 0.3 ? ${floatSumIsExact()}');
  print('abs(-3.5) = ${absOf(-3.5)}, abs(-42) = ${absOf(-42)}');
  print('0xFF + 0x0A = ${hexLiteral()}  (Dart 无二进制字面量)');

  print('\n--- 2. 字符串 ---');
  print(greet('Gopher', 30));
  print('raw: ${windowsPath()}');
  print(banner().trimRight());
  const emoji = '👋 Dart';
  print('"$emoji" code units = ${codeUnitLength(emoji)}, runes = ${runeLength(emoji)}');

  print('\n--- 3. const / final ---');
  print('maxRetries = $maxRetries, defaultPorts = $defaultPorts');
  print('const 列表被规范化: ${constListsAreCanonicalized()}');
  print('普通列表没有结构相等: ${plainListsAreNotEqual()}');
  print('final 每次都是新对象: ${requestTimestamp()} / ${requestTimestamp()}');

  print('\n--- 4. 函数 ---');
  print(buildUser(name: 'alice'));
  print(buildUser(name: 'bob', age: 42, tag: 'admin', active: false));
  print('sumAll([1,2,3]) = ${sumAll([1, 2, 3])}');
  print('sumAll([1,2,3], 100) = ${sumAll([1, 2, 3], 100)}');
  print('sumSpread = ${sumSpread([1, 2], [3, 4])}');

  print('\n--- 5. 函数作为值 / 闭包 ---');
  print('applyOp(add, 3, 4) = ${applyOp(add, 3, 4)}');
  print('applyOp(mul, 3, 4) = ${applyOp(mul, 3, 4)}');
  print('addThenMul(3, 4) = ${addThenMul(3, 4)}');
  final acc = makeAccumulator(start: 10);
  print('accumulator: ${acc(1)}, ${acc(2)}, ${acc(3)}');
  print('循环变量捕获: ${capturedLoopVariables(3)}');

  print('\n--- 6. record ---');
  final (:quotient, :remainder) = divMod(17, 5);
  print('divMod(17, 5) = ($quotient, $remainder)');
  print('divMod(17,5) == (3,2) ? ${divMod(17, 5) == (quotient: 3, remainder: 2)}');
  print('minMax([3,1,4,1,5]) = ${minMax([3, 1, 4, 1, 5])}');

  print('\n--- 7. 静态类型 / dynamic ---');
  print(inferredTypeOf(1));
  // ignore: avoid_print
  print(dynamicDispatch(3.14));
}

代码构成:dart 15 KB · text 11 KB · yaml 379 B

本地运行

zip → 解压 → 执行
$cd examples/ch01-dart-basics && dart pub get && dart run

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • dart analyze(0 告警)、dart test(25 个用例全绿)
查看全部示例