YouTip LogoYouTip

Dart Variables And Types

Variables are the basic units for storing data in a program, and data types determine what values a variable can store. This chapter introduces variable declaration methods in Dart, basic data types, and the important null safety mechanism. * * * ## Variable Declaration: var, final, const Dart provides three keywords for declaring variables, each suitable for different scenarios. Understanding their differences is the first step to learning Dart well. ### var β€” Type-Inferred Variable Variables declared with var have their type automatically inferred from the initial value, and the type cannot be changed once determined. ## Instance void main(){ // Type inference: name's type is inferred as String var name ='TUTORIAL'; // Type inference: age's type is inferred as int var age =10; print('$name already / has been $age years'); // The following will cause an error β€” once the type is determined, you cannot assign a value of another type // name = 123; // Error: cannot assign int to String } TUTORIAL already / has been 10 years > var is not "no type" or "dynamic type" β€” its type is fixed at the moment of assignment. This is completely different from JavaScript's var. ### final β€” Runtime Constant Variables declared with final can only be assigned once, but the assignment can be deferred to runtime. ## Instance void main(){ // final variable: cannot be modified once assigned final currentTime = DateTime.now(); print('Current time: $currentTime'); // Deferred assignment is also allowed final String greeting; greeting ='Hello, TUTORIAL!';// First assignment OK // greeting = 'Hello again'; // Error: final variable cannot be assigned again print(greeting); } Current time: 2026-06-12 10:30:00.000Hello, TUTORIAL! ### const β€” Compile-Time Constant const is more strict than final: its value must be determinable at compile time. ## Instance void main(){ // const must have a determinable value at compile time const siteName ='TUTORIAL'; const maxUsers =100; print('site / website: $siteName, maximum number of users: $maxUsers'); // The following will cause an error β€” DateTime.now() can only be determined at runtime // const currentTime = DateTime.now(); // Error! } site / website: TUTORIAL, maximum number of users: 100 ### Comparison Summary | Keyword | Modifiable | Assignment Timing | Typical Scenarios | | --- | --- | --- | --- | | var | Yes | Any time | Regular variables whose values change | | final | Not modifiable | Runtime-determined | Configuration from API, current time | | const | Not modifiable | Compile-time-determined | Math constants, fixed configuration, color values | > A practical tip: Use final by default. Change it to var only when you find you need to modify it. This habit makes code safer and reduces bugs from accidental modifications. * * * ## Numeric Types: int and double Dart has two numeric types: int (integer) and double (floating-point number). Their common parent class is num. ## Instance void main(){ // int: integer, range is -2^63 to 2^63-1 int viewCount =10000; int negativeNumber =-42; // double: double-precision floating-point number double price =9.99; double pi =3.1415926; // num can accept both int and double num someNumber =10; someNumber =10.5;// Valid print('page views / view count: $viewCount'); print('Price: Β₯$price'); print('pi (Ο€): $pi'); } page views / view count: 10000Price: Β₯9.99pi (Ο€): 3.1415926 ### Common Numeric Methods ## Instance import'dart:math';// Import math library void main(){ int a =-10; double b =3.7; // Absolute value print('a absolute value of: ${a.abs()}');// 10 // Round to integer print('b round off / rounding: ${b.round()}');// 4 // Floor print('b Round Down: ${b.floor()}');// 3 // Ceiling print('b Round Up: ${b.ceil()}');// 4 // String to number int parsed =int.parse('42'); double parsedDouble =double.parse('3.14'); print('parse result: $parsed, $parsedDouble'); // Generate random number (requires import 'dart:math') var random = Random().nextInt(100); print('random number (0-99): $random'); } a absolute value of: 10 b round off / rounding: 4 b Round Down: 3 b Round Up: 4parse result: 42, 3.14random number (0-99): 67 * * * ## Strings: String and Interpolation Syntax String is used to represent text. Dart strings support both single quotes and double quotes. String Interpolation is one of Dart's most convenient features. ## Instance void main(){ // Strings can use single or double quotes String singleQuoted ='Hello'; String doubleQuoted ="World"; // Multi-line strings: use three quotes String multiLine =''' This is First row This is Second row This is the third row - TUTORIAL '''; // String interpolation: use $variableName or ${expression} String site ='TUTORIAL'; int years =10; // $variableName: direct variable reference print('Welcome to $site'); // ${expression}: embed complex expressions print('$site has been with us for ${years + 1} years'); // Escape characters print('Newline character: First row\\ Second row'); print('tab character: column1\\\\t column2'); } Welcome to TUTORIAL TUTORIAL has been with us for 11 yearsNewline character: First rowSecond rowtab character: column1column2 ### Common String Methods ## Instance void main(){ String text =' Hello, TUTORIAL! '; // Trim leading and trailing whitespace print('trim: [${text.trim()}]'); // To uppercase / To lowercase print('uppercase: ${text.toUpperCase()}'); print('lowercase: ${text.toLowerCase()}'); // Whether it contains a substring print('contains TUTORIAL? ${text.contains('TUTORIAL')}'); // Whether it starts with or ends with a string print('withleading space? ${text.startsWith('')}'); print('with!End? ${text.trim().endsWith('!')}'); // String replacement print('Replace: ${text.replaceAll('TUTORIAL', 'DART')}'); // String splitting String csv ='Dart,Flutter,Google'; List items = csv.split(','); print('split result: $items'); // String concatenation print('concatenate / join: '+'Hello'+', '+'World'); } trim: [Hello, TUTORIAL!]uppercase: HELLO, TUTORIAL!lowercase: hello, tutorial!contains TUTORIAL?
← Dart Control FlowDart First Program β†’