dart学习: 📲 环境安装、升级、cheatsheet

在 macos 下安装 dart 语言环境
更新于: 2024-06-02 17:38:58

安装

# 安装
brew tap dart-lang/dart
brew install dart

# 升级
brew upgrade dart

# 检测安装情况(任选1个)
brew info dart
dart --version

hello world

dart 01-hello.dart

void main() {
  print('Hello, World!');
}

基本语法

语法代码
各种变量
void main() {
  var name = 'Voyager I';
  var year = 1977;
  var antennaDiameter = 3.7;
  var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
  var image = {
    'tags': ['saturn'],
    'url': '//path/to/saturn.jpg'
  };
  
  print('$name, $year, $antennaDiameter, $flybyObjects, $image');
}
遍历数组
void main() {
  var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];

  // loop array with index
  for (var i = 0; i < flybyObjects.length; i++) {
    print('$i, ${flybyObjects[i]}');
  }
}

// 如果不关心 index 可以使用 for .. in 
void main() {
  var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
  // loop array with index
  for (var object in flybyObjects) {
    print(object);
  }
}
函数-常规
void main() {
  int fibonacci(int n) {
    if (n == 0 || n == 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
  }

  var result = fibonacci(20);
  print(result);
}
导入
// Importing core libraries
import 'dart:math';

// Importing libraries from external packages
import 'package:test/test.dart';

// Importing files
import 'path/to/my_other_file.dart';
随机
// https://api.dart.dev/stable/3.1.4/dart-math/dart-math-library.html

var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
var doubleValue = Random().nextDouble(); // Value is >= 0.0 and < 1.0.
var boolValue = Random().nextBool(); // true or false, with equal chance.

二进制

实测发现: cannot execute binary file: Exec format error(在linux下执行不了)

dart compile exe --help
dart compile exe 01-hello.dart -o hello-linux --target-os linux