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. Linux 三剑客常用命令

    shell三剑客===================================================grep===================================== ...

  2. Flink 中 DataStream 和 DataSet区别

    DataSet与DataStream的区别.使用 DataSet同DataStream从其接口封装.真实计算Operator有很大的差别,Dataset的实现在flink-javamodule中,而D ...

  3. kali2020-bash: openvas-setup:未找到命令 ,解决办法

    将openvas-setup命令换成 gvm-setup命令即可

  4. kubctl

    kubctl delete 命令:删除资源 根据yaml文件删除对应的资源,但是yaml文件并不会被删除,这样更加高效 delete 描述: 按文件名.stdin.资源和名称或按资源和标签选择器删除资 ...

  5. js 获取鼠标位置的两种方法

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. python 安装fbprophet模块的艰辛历程

    fbprophet这个模块是我目前见过最难装的一个模块,我安装这个包安装了3天,气死我了,需求的依赖包太多,而且对依赖包的版本有极高的要求,所以建议在装这个模块的时候在一个空的虚拟环境下安装,这样依赖 ...

  7. algorithm learning for Leetcode (1)

    Leetcode 算法学习(一) 前言:最近学校要求必须学习C++,着重提升技能板块.为了快速升级,我在GitHub上发现了一个开源的学习号召: https://labuladong.github.i ...

  8. SQL相关知识点

    一.基本概念 数据库术语 数据库(database) - 保存有组织的数据的容器(通常是一个文件或一组文件). 数据表(table) - 某种特定类型数据的结构化清单. 模式(schema) - 关于 ...

  9. c语言动态数组

    动态数组根据用户的需要开创空间 避免造成空间的浪费 #include<stdio.h> #include<stdlib.h> typedef struct { int *par ...

  10. centos 通过yum安装docker-ce报错

    通过yum安装docker-ce报错,是因为本机安装过多次造成的,如下所示,需要解决掉冲突依赖,从新安装 1 从 https://mirrors.aliyun.com/docker-ce/linux/ ...