Dart is an open source, structured programming language for creating complex, browser-based web applications.

first dart demo

main() {
var d = "Dart";
String w = "World";
print("Hello $w! I love $d"); // Hello World! I love Dart
}

string interpolation

void main() {
var h = "Hello";
final w = "World";
print('$h $w'); // Hello World
print(r'$h $w'); // $h $w var helloWorld = "Hello " "World";
print(helloWorld); // Hello World
print("${helloWorld.toUpperCase()}"); // HELLO WORLD
print("The answer is ${5 + 10}"); // The answer is 15 var multiline = """
<div id='greeting'>
"Hello World"
</div>""";
print(multiline);
var o = Object();
print(o.toString()); // Instance of 'Object'
print("$o"); // // Instance of 'Object'
}

Multiline strings ignore first line break following """ and also can contain both single and double quotes.

dart class in use

class Greeter {
var greeting; // public property
var _name; // private property
sayHello() => "$greeting ${this.name}"; get name => _name; // getter method for _name
set name(value) => _name = value; // setter method for _name
} main() {
var greeter = Greeter();
greeter.greeting = "Hello ";
greeter.name = "World";
print(greeter.sayHello()); // Hello World
}

Implied interface definitions

Dart has interfaces just like Java and C#, but in Dart, you use the class structure to define an interface. This works on the basis that all classes define an implicit interface on their public members.

class Welcomer {
printGreeting() => print("Hello ${name}");
var name;
} class Greeter implements Welcomer {
printGreeting() => print("Greetings ${name}");
var name;
} void sayHello(Welcomer welcomer) {
welcomer.printGreeting();
} main() {
var welcomer = Welcomer();
welcomer.name = "Tom";
sayHello(welcomer); // Hello Tom
var greeter = Greeter();
greeter.name = "Tom";
sayHello(greeter); // Greetings Tom
}

Factory constructors to provide default implementations

abstract class IGreetable {
String sayHello(String name);
factory IGreetable() => Greeter();
} class Greeter implements IGreetable {
sayHello(name) => "Hello $name";
} void main() {
IGreetable myGreetable = IGreetable();
var message = myGreetable.sayHello("Dart");
print(message); // Hello Dart
}

Libraries and scope

library "my_library"; // Declares that file is a library
import "../lib/my_other_library.dart"; // Imports another library from a different folder part "greeter.dart"; // Includes other source files (containing Greeter class)
part "leaver.dart"; greetFunc() { // Defines function in top- level library scope
var g = new Greeter(); // Uses class from greeter.dart file
sayHello(g); // Calls function in top-level scope of my_other_library
}

To avoid naming conflicts, you can use as keywords.

import "../lib/my_other_library.dart" as other;

Functions as first-class objects

String sayHello(name) => "Hello $name"; // Declares function using function shorthand
main() {
var myFunc = sayHello; // Assigns function into variable
print(myFunc("World")); // Calls function stored in variable
var mySumFunc = (a, b) => a + b; // Defines anonymous function
var c = mySumFunc(1, 2); // Calls anonymous function
print(c); //
}

Mixins

Mixins are a way of reusing code in multiple class hierarchies. The following class can act as a mixin:

class Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
} class PilotedCraft with Piloted {} // now has the astronauts field as well as the describeCrew() method. main(List<String> args) {
var plotedCraft = PilotedCraft();
plotedCraft.astronauts = 23;
plotedCraft.describeCrew(); // Number of astronauts: 23
}

To specify that only certain types can use the mixin.

mixin MusicalPerformer on Musician {
// ···
}

spread operator (...) and the null-aware spread operator (...?)(Dart 2.3)

you can use the spread operator (...) to insert all the elements of a list into another list:

var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);

If the expression to the right of the spread operator might be null, you can avoid exceptions by using a null-aware spread operator (...?):

var list;
var list2 = [0, ...?list];
assert(list2.length == 1);

collection if and collection for(Dart 2.3)

using collection if to create a list with three or four items in it:

var nav = [
'Home',
'Furniture',
'Plants',
if (promoActive) 'Outlet'
];

using collection for to manipulate the items of a list before adding them to another list:

var listOfInts = [1, 2, 3];
var listOfStrings = [
'#0',
for (var i in listOfInts) '#$i'
];
assert(listOfStrings[1] == '#1');

Optional parameters

Optional parameters can be either named or positional, but not both.

Named parameters

When calling a function, you can specify named parameters using paramName: value. For example:

// define method which parameters with {}
void enableFlags({bool bold, bool hidden}) {...} // call method
enableFlags(bold: true, hidden: false);

Although named parameters are a kind of optional parameter, you can annotate them with @required to indicate that the parameter is mandatory.

const Scrollbar({Key key, @required Widget child})
Positional parameters

Wrapping a set of function parameters in [] marks them as optional positional parameters:

String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
} assert(say('Bob', 'Howdy') == 'Bob says Howdy');
assert(say('Bob', 'Howdy', 'smoke signal') =='Bob says Howdy with a smoke signal');
Default parameter values

Your function can use = to define default values for both named and positional parameters. The default values must be compile-time constants. If no default value is provided, the default value is null.

String say(String from, String msg, [String device = 'carrier pigeon', String mood]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
if (mood != null) {
result = '$result (in a $mood mood)';
}
return result;
} assert(say('Bob', 'Howdy') =='Bob says Howdy with a carrier pigeon');

division use / or ~/

assert(5 / 2 == 2.5); // Result is a double
assert(5 ~/ 2 == 2); // Result is an int
assert(5 % 2 == 1); // Remainder

Type test operators

The as, is, and is! operators are handy for checking types at runtime.

if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}

Conditional expressions

Dart has two operators that let you concisely evaluate expressions that might otherwise require if-else statements:

  • condition ? expr1 : expr2:

If condition is true, evaluates expr1 (and returns its value); otherwise, evaluates and returns the value of expr2.

var visibility = isPublic ? 'public' : 'private';
  • expr1 ?? expr2

If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2.

// If the boolean expression tests for null, consider using ??.
String playerName(String name) => name ?? 'Guest'; // Slightly longer version uses ?: operator.
String playerName(String name) => name != null ? name : 'Guest'; // Very long version uses if-else statement.
String playerName(String name) {
if (name != null) {
return name;
} else {
return 'Guest';
}
}

Cascade notation (..)

Cascades (..) allow you to make a sequence of operations on the same object. In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

// first way
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!')); // second way
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));

give an example:

class Person {
String name;
int age; Person({this.name, this.age});
} main(List<String> args) {
Person person = Person()
..age = 26
..name = "huhx";
print('${person.age} name ${person.name}'); // 26 name huhx
person
..age = 27
..name = "gohuhx";
print('${person.age} name ${person.name}'); // 27 name gohuhx
}

operator ?.

import 'dart:math';

main(List<String> args) {
var p = Point(2, 2);
print(p.y); // 2
var p2;
print(p2); // null
print(p2?.y); // null
}

Getting an object’s type

To get an object’s type at runtime, you can use Object’s runtimeType property, which returns a Type object.

import 'dart:math';

main(List<String> args) {
var p = Point(2, 2);
print(p.runtimeType); // Point<int>
var s = "string";
print(s.runtimeType); // String
}

Constructors

class Point {
double x, y; Point(double x, double y) {
// There's a better way to do this, stay tuned.
this.x = x;
this.y = y;
}
} // better way to construct
class Point {
double x, y; // Syntactic sugar for setting x and y before the constructor body runs.
Point(this.x, this.y);
}

Extension

Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries.

extension NumberParsing on String {
int parseInt() {
return int.parse(this);
}
} main(List<String> args) {
print('42'.parseInt()); // 42
}

dart基础---->dart语法入门的更多相关文章

  1. MAUI新生-XAML语法基础:语法入门Element&Property&Event&Command

    一.XAML(MAUI的XAML)和HTML 两者相似,都是标签语言(也叫标记)组成的树形文档.每个标签元素,可视为一个对象,通过"键=值"形式的标签属性(Attribute),为 ...

  2. Dart:2.通过一个简单程序来理解Dart基础语法

    一 . 一个简单的 Dart 程序 // 这是程序执行的入口. main() { var number = 42; // 定义并初始化一个变量. printNumber(number); // 调用一 ...

  3. Java基础语法入门01

    Java基础语法入门01 学习java你要先进行去了解JDK,JRE,JVM JDK Java开发工具包 JRE Java语言开发的运行环境 JVM Java虚拟机,用于Java语言的跨平台所用. 当 ...

  4. Dart基础学习02--变量及内置类型

    Dart基础学习02--变量及内置类型 Dart中的变量 首先看一个变量的定义和赋值 var name = 'Bob'; 在Dart中变量名都是引用,这里的name就是一个指向值为Bob的字符串的引用 ...

  5. Flutter学习笔记--Dart基础

    前言 Flutter使用Dart语言开发, Dart是面向对象编程语言, 由Google2011年推出, 目前最新版本是2.4.0. 工欲善其事,必先利其器. 为了更好的开发Flutter应用, 我们 ...

  6. Dart 基础重点截取 Dart 2 20180417

    官网教程 https://www.dartlang.org/guides/language/language-tour dart是一个单线程的语言,没有多线程 Final and const If y ...

  7. Dart基础学习01--走近Dart

    什么是Dart 在Dart的官网上是这样介绍Dart的: Dart is an open-source, scalable programming language, with robust libr ...

  8. jQuery学习笔记 - 基础知识扫盲入门篇

    jQuery学习笔记 - 基础知识扫盲入门篇 2013-06-16 18:42 by 全新时代, 11 阅读, 0 评论, 收藏, 编辑 1.为什么要使用jQuery? 提供了强大的功能函数解决浏览器 ...

  9. [转]前端利器:SASS基础与Compass入门

    [转]前端利器:SASS基础与Compass入门 SASS是Syntactically Awesome Stylesheete Sass的缩写,它是css的一个开发工具,提供了很多便利和简单的语法,让 ...

  10. 第87节:Java中的Bootstrap基础与SQL入门

    第87节:Java中的Bootstrap基础与SQL入门 前言复习 什么是JQ? : write less do more 写更少的代码,做更多的事 找出所有兄弟: $("div" ...

随机推荐

  1. docker-compose实践(携程apollo项目)

    docker-compose使用开源镜像启动容器 以携程apollo项目为例,使用docker-compose部署单节点模式 创建apollo文件夹,vim一个新的docker-compose.yam ...

  2. react intl 国际化

    方案描述:由于采用单页面,所以按钮切换时会刷新页面 1.安装 react-intl  babel-plugin-react-intl json-loader npm i react-intl babe ...

  3. gitt如何将本地分支同远程分支进行关联

    将本地分支同远程分支进行关联,1.本地已经创建了分支test(test,是master以外自己创建的分支),而远程没有2种方法在远程创建分支test,并与本地分支进行关联: 方法1: git push ...

  4. UEC++学习(2)

    第三章 断言 第一节 简单的断言 断言让程序的进程中断,方便程序员发现在哪里发生了问题. AGameBase * GameBase = nullptr; check(false); check(Gam ...

  5. ucharts的区域图、折线图(有x轴的),修改x轴显示为隔一个显示

    1.原本的显示方式: 2.想要的效果: 3.这边我使用的是uchart的组件,在uni_modules > qiun-data-charts > js_sdk > u-charts, ...

  6. Shell 更多结构化命令(流程控制)

    更多的结构化命令 上一章里,你看到了如何通过检查命令的输出和变量的值来改变 shell 脚本程序的流程.本章会继续介绍能够控制 shell 脚本流程的结构化命令.你会了解如何重复一些过程和命令,也就是 ...

  7. 关于IllegalMonitorStateException异常的解释之一

    注意 在同步控制方法或同步控制块里调用wait(),notify()和notifyAll().如果在非同步控制方法里调用这些方法,程序能通过编译,但运行的时候,将得到IllegalMonitorSta ...

  8. 位运算与MOD快速幂详细知识点

    最近写的一些题目设计到了数论的取模 如下题 链接:https://ac.nowcoder.com/acm/contest/3003/G来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制: ...

  9. 通过网页或者移动设备链接跳转qq(tim)添加好友(群)

    首先需要去qq群官方,然后点记加群组件,然后选择群,复制对应的代码即可 登录到QQ群官网 点击加群组件 选择群,选择网页还是移动设备 复制代码 示例: <html> <head> ...

  10. xlsx合并单元格简单介绍

    在使用xlsx导出excel表格的时候,有时候我们需要将某些表格进行合并,该如何做呢,代码如下: import XLSX from 'xlsx'; // ... // xlsxData 是 Excel ...