资讯动态

Dart - Dart SDK、Hello World 案例、变量声明、常量声明、常量 final、字符串类型

发布时间:2026/8/14 19:28:45 来源:尧图企业网站定制
一、Dart SDKDart SDK 官方网址https://dart.dev/get-dart/archive下载完成、配置好环境变量后执行dart --version指令即可查看 Dart 版本二、Hello World 案例在 VScode 中安装 Dart 插件创建并编辑 Dart 文件01_hello_world.dartvoidmain(){print(Hello, World!);}执行dart run 【文件名】.dart指令运行 Dart 文件三、Hello World 案例解读1、核心概念在 Dart 中main 函数是程序的入口点每一个可执行的 Dart 程序都必须包含一个 main 函数程序运行时会首先执行 main 函数中的代码void 表示函数不返回任何值对于 main 函数通常使用 void因为它不需要返回任何东西print 是 Dart 标准库提供的函数用于在控制台输出信息2、注意事项Dart 语句以分号结尾print(Hello);// 正确print(Hello)// 错误Dart 中既可以使用单引号也可以使用双引号print(Hello, World!);print(Hello, World!);大小写敏感print(Hello);// 正确Print(Hello);// 错误四、变量声明1、演示var 是 Dart 中最常用的变量声明方式Dart 会自动推断变量的类型varnameAlice;varage25;varheight1.68;varisStudenttrue;print(Name:$name);print(Age:$age);print(Height:$height);print(Is Student:$isStudent);Name: Alice Age: 25 Height: 1.68 Is Student: true也可以显式地指定变量类型int count10;double price99.9;StringmessageWelcome;bool isActivetrue;print(Count:$count);print(Price:$price);print(Message:$message);print(Is Active:$isActive);# 输出结果 Count: 10 Price: 99.9 Message: Welcome Is Active: true2、变量命名规则合法的变量名varnameAlice;// 字母开头varuserNameBob;// 驼峰命名法varuser_nameCharlie;// 下划线命名法var_privateSecret;// 下划线开头varage230;// 包含数字不在开头非法的变量名var2nameAlice;// 不能以数字开头varmy-nameBob;// 不能包含连字符varmy nameCharlie;// 不能包含空格varclassDart;// 不能使用保留字3、注意事项不能使用未初始化的变量int count;double price;Stringname;bool isActive;print(count);print(price);print(name);print(isActive);一旦 Dart 推断出变量的类型就不能改变varvalue10;// value 是 int 类型value20;// 仍然是 int 类型valuetext;// 错误不能赋值 String 类型4、扩展多变量声明var(x,y,z)(1,2,3);print(x$x, y$y, z$z);vara1,b2,c3;print(a$a, b$b, c$c);五、常量声明1、基本介绍const 用于声明编译时常量这些值在程序运行前就已经确定且不可改变2、演示// 显式类型声明constint maxItems100;constdouble pi3.14159;constStringappNameDart Learning;// 自动类型推断constmaxItems100;constpi3.14159;constappNameDart Learning;3、const 集合const 可以用于声明不可变的集合尝试修改会报错constListintnumbers[1,2,3,4,5];constMapString,intscores{Alice:95,Bob:88};4、注意事项const 用于声明编译时常量值必须在编译时确定不能用于运行时计算的值// 允许constint a10;constint b20;constint sumab;// 不允许constnowDateTime.now();六、常量 final1、基本介绍final 用于声明只能被赋值一次的变量是 Dart 中另一个重要的不可变类型声明方式final 变量可以在运行时赋值final 列表变量引用不可变但内容可变2、演示// 显式类型声明finalStringnameAlice;finalint age25;// 自动类型推断finalnameAlice;finalage25;// 运行时赋值finalDateTimenowDateTime.now();// final 列表内容可变finalListintnumbers[1,2,3];numbers.add(4);七、字符串类型1、基本介绍Dart 支持单引号和双引号创建字符串StringsingleQuoteHello;StringdoubleQuoteHello;多行字符串voidmain(){Stringmultiline This is a multiline string. It can span multiple lines. Very convenient! ;print(multiline);}# 输出结果 This is a multiline string. It can span multiple lines. Very convenient!字符串拼接// 使用 运算符StringcombinedDart is awesome!;print(combined);// 使用 * 运算符StringrepeatedHa *3;print(repeated);字符串插值StringnameAlice;int age25;// 简单插值StringgreetingHello,$name! You are$ageyears old.;// 表达式插值StringexpressionAge next year:${age1};print(greeting);print(expression);2、常用方法大小写转换StringtextHello World;print(Original:$text);print(Upper:${text.toUpperCase()});print(Lower:${text.toLowerCase()});字符串查找StringtextHello World;// 包含检查print(Contains World: ${text.contains(World)});print(Contains Dart: ${text.contains(Dart)});// 开头结尾检查print(Starts with Hello: ${text.startsWith(Hello)});print(Ends with World: ${text.endsWith(World)});// 查找位置print(Index of o: ${text.indexOf(o)});print(Last index of o: ${text.lastIndexOf(o)});# 输出结果 Contains World: true Contains Dart: false Starts with Hello: true Ends with World: true Index of o: 4 Last index of o: 7字符串截取StringtextHello World;// 截取子串print(Substring(0, 5):${text.substring(0,5)});print(Substring(6):${text.substring(6)});// 分割字符串ListStringwordstext.split( );print(Split:$words);// 去除空白StringwithSpaces Hello ;print(Trim: ${withSpaces.trim()});print(Trim left: ${withSpaces.trimLeft()});print(Trim right: ${withSpaces.trimRight()});# 输出结果 Substring(0, 5): Hello Substring(6): World Split: [Hello, World] Trim: Hello Trim left: Hello Trim right: Hello字符串替换StringtextHello World;// 替换所有Stringreplacedtext.replaceAll(o,X);print(Replace all:$replaced);// 替换首个StringreplacedFirsttext.replaceFirst(o,X);print(Replace first:$replacedFirst);// 替换字符串StringreplacedStrtext.replaceRange(0,5,Hi);print(Replace range:$replacedStr);# 输出结果 Replace all: HellX WXrld Replace first: HellX World Replace range: Hi World3、字符串属性StringtextHello;print(Length:${text.length});print(Hash code:${text.hashCode});print(Runtime type:${text.runtimeType});Stringunicode你好;print(Unicode length:${unicode.length});print(Code units:${unicode.codeUnits});Stringt ;print(Is empty:${t.isEmpty});print(Is not empty:${t.isNotEmpty});# 输出结果 Length: 5 Hash code: 828172268 Runtime type: String Unicode length: 2 Code units: [20320, 22909] Is empty: false Is not empty: true4、注意事项字符串是不可变的// 错误StringtextHello;text[0]J;print(newText);// 正确StringtextHello;StringnewTextJ${text.substring(1)};print(newText);字符串索引StringtextHello;// 访问字符print(First char:${text[0]});// 使用 runes 处理 Unicodeprint(Runes:${text.runes});# 输出结果 First char: H Runes: (72, 101, 108, 108, 111)null 安全// 错误可能为 nullString?nullable;print(nullable.length);// 正确空安全检查String?nullable;print(Length:${nullable?.length??0});// 正确提供默认值String?nullable;print(Value: ${nullable ?? default});5、扩展1Raw 字符串普通字符串\n是换行符StringnormalLine 1\nLine 2;print(Normal:);print(normal);# 输出结果 Normal: Line 1 Line 2Raw 字符串\n是字面量符StringrawrLine 1\nLine 2;print(Raw:);print(raw);# 输出结果 Raw: Line 1\nLine 22StringBuffer 性能优化大量字符串拼接时使用 StringBuffer 更高效StringBufferbufferStringBuffer();for(int i0;i1000;i){buffer.write(Item$i, );}Stringresultbuffer.toString();print(Length:${result.length});3字符串与其他类型转换数字转字符串int num42;StringfromIntnum.toString();Stringformattednum.toStringAsFixed(2);print(fromInt);print(formatted);# 输出结果 42 42.00字符串转数字int parsedIntint.parse(123);double parsedDoubledouble.parse(3.14);print(parsedInt);print(parsedDouble);# 输出结果 123 3.14字符串转列表Stringcsvapple,banana,orange;ListStringfruitscsv.split(,);print(fruits);# 输出结果 [apple, banana, orange]列表转字符串ListStringcolors[red,green,blue];Stringjoinedcolors.join();print(joined);# 输出结果 redgreenblue

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价