Chức năng ẩn danh trong php geeksforgeeks
Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic Show
Khi một biến được sử dụng trong biểu thức được xác định trong phạm vi cha, nó sẽ được ngầm định theo giá trị. Trong ví dụ sau, các hàm $fn1 và $fn2 hoạt động giống nhau Example #1 Arrow functions capture variables by value automatically
The above example will output This also works if the arrow functions are nested Example #2 Arrow functions capture variables by value automatically, even when nested
Tương tự như các hàm ẩn danh, cú pháp hàm mũi tên cho phép các chữ ký hàm tùy ý, bao gồm tham số và kiểu trả về, giá trị mặc định, biến thể, cũng như chuyển và trả về tham chiếu theo tham chiếu. Tất cả những điều sau đây là ví dụ hợp lệ của các chức năng mũi tên Ví dụ #3 Ví dụ về hàm mũi tên
Các hàm mũi tên sử dụng liên kết biến theo giá trị. Điều này gần tương đương với việc thực hiện một Trang này chỉ cho bạn cách sử dụng từng tính năng chính của Dart, từ các biến và toán tử đến các lớp và thư viện, với giả định rằng bạn đã biết cách lập trình bằng ngôn ngữ khác. Để có phần giới thiệu ngắn gọn hơn, ít đầy đủ hơn về ngôn ngữ, hãy xem trang mẫu ngôn ngữ Để tìm hiểu thêm về các thư viện cốt lõi của Dart, hãy xem chuyến tham quan thư viện. Bất cứ khi nào bạn muốn biết thêm chi tiết về một tính năng ngôn ngữ, hãy tham khảo đặc tả ngôn ngữ Dart Ghi chú. Bạn có thể chơi với hầu hết các tính năng ngôn ngữ của Dart bằng DartPad (tìm hiểu thêm). Mở DartPad Trang này sử dụng DartPads được nhúng để hiển thị một số ví dụ. Nếu bạn thấy các ô trống thay vì DartPad, hãy truy cập trang xử lý sự cố DartPad Một chương trình phi tiêu cơ bảnĐoạn mã sau sử dụng nhiều tính năng cơ bản nhất của Dart
Đây là những gì chương trình này sử dụng áp dụng cho tất cả (hoặc gần như tất cả) ứng dụng Phi tiêu 14Nhận xét một dòng. Dart cũng hỗ trợ nhận xét nhiều dòng và tài liệu. Để biết chi tiết, xem. 15Một loại đặc biệt cho biết một giá trị không bao giờ được sử dụng. Các hàm như 16 và 17 không trả về giá trị một cách rõ ràng có kiểu trả về 15. 19Loại khác, biểu thị số nguyên. Một số bổ sung là 20, 21 và 22. 23Một số chữ. Số chữ là một loại hằng số thời gian biên dịch. 24Một cách thuận tiện để hiển thị đầu ra. 25 (hoặc 26)Một chuỗi ký tự. 27 (hoặc 28)Nội suy chuỗi. bao gồm một biến hoặc chuỗi của biểu thức tương đương bên trong một chuỗi ký tự. For more information, see . 17Chức năng cấp cao nhất, bắt buộc, đặc biệt nơi bắt đầu thực thi ứng dụng. Để biết thêm thông tin, xem. 30Một cách để khai báo một biến mà không chỉ định loại của nó. Loại của biến này ( 19) được xác định bởi giá trị ban đầu của nó ( 23)Ghi chú. Mã của trang web này tuân theo các quy ước trong hướng dẫn kiểu Dart khái niệm quan trọngKhi bạn tìm hiểu về ngôn ngữ Dart, hãy ghi nhớ những thông tin và khái niệm này
KeywordsThe following table lists the words that the Dart language treats specially 2 2 1 2 2export 2 2 1 3 2 2 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 3 2 2 2 Avoid using these words as identifiers. However, if necessary, the keywords marked with superscripts can be identifiers
All other words in the table are reserved words, which can’t be identifiers VariablesHere’s an example of creating a variable and initializing it
Variables store references. The variable called 64 contains a reference to a 20 object with a value of “Bob”The type of the 64 variable is inferred to be 20, but you can change that type by specifying it. If an object isn’t restricted to a single type, specify the 35 type (or 47 if necessary)
Một tùy chọn khác là khai báo rõ ràng loại sẽ được suy ra
Note. This page follows the of using 30, rather than type annotations, for local variablesDefault valueUninitialized variables that have a nullable type have an initial value of 33. (If you haven’t opted into null safety, then every variable has a nullable type. ) Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects
Note. Production code ignores the 72 call. During development, on the other hand, 73 throws an exception if condition is false. For details, see If you enable null safety, then you must initialize the values of non-nullable variables before you use them
You don’t have to initialize a local variable where it’s declared, but you do need to assign it a value before it’s used. For example, the following code is valid because Dart can detect that 74 is non-null by the time it’s passed to 24
Top-level and class variables are lazily initialized; the initialization code runs the first time the variable is used Late variablesDart 2. 12 added the 76 modifier, which has two use cases
Often Dart’s control flow analysis can detect when a non-nullable variable is set to a non-null value before it’s used, but sometimes analysis fails. Two common cases are top-level variables and instance variables. Dart often can’t determine whether they’re set, so it doesn’t try If you’re sure that a variable is set before it’s used, but Dart disagrees, you can fix the error by marking the variable as 76
If you fail to initialize a 76 variable, a runtime error occurs when the variable is usedWhen you mark a variable as 76 but initialize it at its declaration, then the initializer runs the first time the variable is used. This lazy initialization is handy in a couple of cases
In the following example, if the 81 variable is never used, then the expensive 82 function is never called
Final and constIf you never intend to change a variable, use 83 or 84, either instead of 30 or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant. (Const variables are implicitly final. )Note. can be 83 but not 84Here’s an example of creating and setting a 83 variable
You can’t change the value of a 83 variable 0Sử dụng 84 cho các biến mà bạn muốn là hằng số thời gian biên dịch. If the const variable is at the class level, mark it 91. Where you declare the variable, set the value to a compile-time constant such as a number or string literal, a const variable, or the result of an arithmetic operation on constant numbers 1The 84 keyword isn’t just for declaring constant variables. You can also use it to create constant values, as well as to declare constructors that create constant values. Any variable can have a constant value 2You can omit 84 from the initializing expression of a 84 declaration, like for 95 above. For details, see You can change the value of a non-final, non-const variable, even if it used to have a 84 value 3You can’t change the value of a 84 variable 4You can define constants that use ( 98 and 99), , and ( 01 and 02) 5Note. Although a 83 object cannot be modified, its fields can be changed. In comparison, a 84 object and its fields cannot be changed. they’re immutableFor more information on using 84 to create constant values, see , , and Built-in typesThe Dart language has special support for the following
This support includes the ability to create objects using literals. For example, 18 is a string literal, and 19 is a boolean literalBởi vì mọi biến trong Dart đề cập đến một đối tượng—một thể hiện của một lớp—bạn thường có thể sử dụng các hàm tạo để khởi tạo các biến. Some of the built-in types have their own constructors. For example, you can use the 20 constructor to create a mapSome other types also have special roles in the Dart language
The 35, 45, 17, and 27 classes have special roles in the class hierarchy, as described in the section of Understanding null safetyNumbersDart numbers come in two flavors 19Integer values no larger than 64 bits, depending on the platform. On native platforms, values can be from -263 to 263 - 1. On the web, integer values are represented as JavaScript numbers (64-bit floating-point values with no fractional part) and can be from -253 to 253 - 1 0764-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard Both 19 and 07 are subtypes of 40. The num type includes basic operators such as +, -, /, and *, and is also where you’ll find 41, 42, and 43, among other methods. (Bitwise operators, such as >>, are defined in the 19 class. ) If num and its subtypes don’t have what you’re looking for, the dart. math library mightSố nguyên là số không có dấu thập phân. Here are some examples of defining integer literals 6If a number includes a decimal, it is a double. Here are some examples of defining double literals 7You can also declare a variable as a num. If you do this, the variable can have both integer and double values 8Integer literals are automatically converted to doubles when necessary 9Here’s how you turn a string into a number, or vice versa 0The 19 type specifies the traditional bitwise shift ( 46, 47, 48), complement ( 49), AND ( 50), OR ( 51), and XOR ( 52) operators, which are useful for manipulating and masking flags in bit fields. For example 1For more examples, see the section Literal numbers are compile-time constants. Many arithmetic expressions are also compile-time constants, as long as their operands are compile-time constants that evaluate to numbers 2For more information, see Numbers in Dart StringsA Dart string ( 20 object) holds a sequence of UTF-16 code units. You can use either single or double quotes to create a string 3You can put the value of an expression inside a string by using 54 55 56. If the expression is an identifier, you can skip the {}. To get the string corresponding to an object, Dart calls the object’s 57 method 4Note. The 58 operator tests whether two objects are equivalent. Two strings are equivalent if they contain the same sequence of code unitsYou can concatenate strings using adjacent string literals or the 59 operator 5Another way to create a multi-line string. use a triple quote with either single or double quotation marks 6You can create a “raw” string by prefixing it with 60 7See for details on how to express Unicode characters in a string Literal strings are compile-time constants, as long as any interpolated expression is a compile-time constant that evaluates to null or a numeric, string, or boolean value 8For more information on using strings, see BooleansTo represent boolean values, Dart has a type named 22. Only two objects have type bool. the boolean literals 19 and 63, which are both compile-time constantsDart’s type safety means that you can’t use code like 64 or 65. Instead, explicitly check for values, like this 9ListsPerhaps the most common collection in nearly every programming language is the array, or ordered group of objects. In Dart, arrays are 21 objects, so most people just call them listsDart list literals are denoted by a comma separated list of expressions or values, enclosed in square brackets ( 67). Here’s a simple Dart list 0Note. Dart infers that 68 has type 48. If you try to add non-integer objects to this list, the analyzer or runtime raises an error. For more information, read about You can add a comma after the last item in a Dart collection literal. This trailing comma doesn’t affect the collection, but it can help prevent copy-paste errors 1Lists use zero-based indexing, where 0 is the index of the first value and 70 is the index of the last value. You can get a list’s length using the 71 property and access a list’s values using the subscript operator ( 67) 2To create a list that’s a compile-time constant, add 84 before the list literal 3Dart supports the spread operator ( 01) and the null-aware spread operator ( 02), which provide a concise way to insert multiple values into a collectionFor example, you can use the spread operator ( 01) to insert all the values of a list into another list 4If the expression to the right of the spread operator might be null, you can avoid exceptions by using a null-aware spread operator ( 02) 5For more details and examples of using the spread operator, see the spread operator proposal Dart also offers collection if and collection for, which you can use to build collections using conditionals ( 00) and repetition ( 79)Here’s an example of using collection if to create a list with three or four items in it 6Here’s an example of using collection for to manipulate the items of a list before adding them to another list 7For more details and examples of using collection 00 and 79, see the control flow collections proposalThe List type has many handy methods for manipulating lists. For more information about lists, see and SetsA set in Dart is an unordered collection of unique items. Dart support for sets is provided by set literals and the 11 typeHere is a simple Dart set, created using a set literal 8Note. Dart infers that 83 has the type 84. If you try to add the wrong type of value to the set, the analyzer or runtime raises an error. For more information, read about To create an empty set, use 85 preceded by a type argument, or assign 85 to a variable of type 11 9Set or map? The syntax for map literals is similar to that for set literals. Because map literals came first, 85 defaults to the 12 type. If you forget the type annotation on 85 or the variable it’s assigned to, then Dart creates an object of type 91Add items to an existing set using the 92 or 93 methods 0Use 71 to get the number of items in the set 1To create a set that’s a compile-time constant, add 84 before the set literal 2Sets support spread operators ( 01 and 02) and collection 00 and 79, just like lists do. For more information, see the and discussionsFor more information about sets, see and MapsIn general, a map is an object that associates keys and values. Cả khóa và giá trị đều có thể là bất kỳ loại đối tượng nào. Mỗi khóa chỉ xuất hiện một lần nhưng bạn có thể sử dụng cùng một giá trị nhiều lần. Hỗ trợ phi tiêu cho bản đồ được cung cấp bởi chữ bản đồ và loại 12Dưới đây là một vài bản đồ Phi tiêu đơn giản, được tạo bằng chữ bản đồ 3Ghi chú. Phi tiêu suy ra rằng 01 có loại 02 và 03 có loại 04. Nếu bạn cố gắng thêm loại giá trị sai vào bản đồ, bộ phân tích hoặc bộ thực thi sẽ phát sinh lỗi. Để biết thêm thông tin, đọc vềBạn có thể tạo các đối tượng giống nhau bằng cách sử dụng hàm tạo Bản đồ 4Ghi chú. Nếu bạn đến từ một ngôn ngữ như C# hoặc Java, bạn có thể sẽ thấy 05 thay vì chỉ 20. Trong Dart, từ khóa 07 là tùy chọn. Để biết chi tiết, xemThêm cặp khóa-giá trị mới vào bản đồ hiện có bằng cách sử dụng toán tử gán chỉ số dưới ( 08) 5Truy xuất một giá trị từ bản đồ bằng toán tử chỉ số dưới ( 67) 6Nếu bạn tìm một chiếc chìa khóa không có trong bản đồ, bạn sẽ nhận lại được 33 7Sử dụng 71 để nhận số cặp khóa-giá trị trong bản đồ 8Để tạo bản đồ là hằng số thời gian biên dịch, hãy thêm 84 trước chữ bản đồ 9Bản đồ hỗ trợ các toán tử trải rộng ( 01 và 02) và bộ sưu tập 00 và 79, giống như danh sách. Để biết chi tiết và ví dụ, hãy xem đề xuất toán tử trải rộng và đề xuất bộ sưu tập luồng điều khiểnĐể biết thêm thông tin về bản đồ, hãy xem phần và phạm vi bảo hiểm của chuyến tham quan thư viện về Các cụm rune và graphemeIn Dart, runes expose the Unicode code points of a string. You can use the characters package to view or manipulate user-perceived characters, also known as Unicode defines a unique numeric value for each letter, digit, and symbol used in all of the world’s writing systems. Because a Dart string is a sequence of UTF-16 code units, expressing Unicode code points within a string requires special syntax. The usual way to express a Unicode code point is 18, where XXXX is a 4-digit hexadecimal value. Ví dụ, ký tự trái tim (♥) là 19. To specify more or less than 4 hex digits, place the value in curly brackets. For example, the laughing emoji (😆) is 20If you need to read or write individual Unicode characters, use the 14 getter defined on String by the characters package. The returned 22 object is the string as a sequence of grapheme clusters. Here’s an example of using the characters API 0The output, depending on your environment, looks something like this 1For details on using the characters package to manipulate strings, see the example and API reference for the characters package SymbolsA 15 object represents an operator or identifier declared in a Dart program. You might never need to use symbols, but they’re invaluable for APIs that refer to identifiers by name, because minification changes identifier names but not identifier symbolsTo get the symbol for an identifier, use a symbol literal, which is just 24 followed by the identifier 2Symbol literals are compile-time constants FunctionsDart is a true object-oriented language, so even functions are objects and have a type, Function. This means that functions can be assigned to variables or passed as arguments to other functions. You can also call an instance of a Dart class as if it were a function. For details, see Here’s an example of implementing a function 3Although Effective Dart recommends , the function still works if you omit the types 4For functions that contain just one expression, you can use a shorthand syntax 5The 25 syntax is a shorthand for 26. The 27 notation is sometimes referred to as arrow syntaxNote. Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an there, but you can use a ParametersA function can have any number of required positional parameters. These can be followed either by named parameters or by optional positional parameters (but not both) Note. Some APIs—notably Flutter widget constructors—use only named parameters, even for parameters that are mandatory. See the next section for details You can use when you pass arguments to a function or when you define function parameters Named parametersNamed parameters are optional unless they’re explicitly marked as 28When defining a function, use 29 to specify named parameters. If you don’t provide a default value or mark a named parameter as 28, their types must be nullable as their default value will be 33 6When calling a function, you can specify named arguments using 32. For example 7To define a default value for a named parameter besides 33, use 34 to specify a default value. The specified value must be a compile-time constant. For example 8If you instead want a named parameter to be mandatory, requiring callers to provide a value for the parameter, annotate them with 28 9If someone tries to create a 36 without specifying the 37 argument, then the analyzer reports an issueNote. A parameter marked as 28 can still be nullable 0You might want to place positional arguments first, but Dart doesn’t require it. Dart allows named arguments to be placed anywhere in the argument list when it suits your API 1Optional positional parametersWrapping a set of function parameters in 67 marks them as optional positional parameters. If you don’t provide a default value, their types must be nullable as their default value will be 33 2Here’s an example of calling this function without the optional parameter 3And here’s an example of calling this function with the third parameter 4To define a default value for an optional positional parameter besides 33, use 34 to specify a default value. Giá trị được chỉ định phải là hằng số thời gian biên dịch. For example 5The main() functionEvery app must have a top-level 17 function, which serves as the entrypoint to the app. The 17 function returns 15 and has an optional 46 parameter for argumentsHere’s a simple 17 function 6Here’s an example of the 17 function for a command-line app that takes arguments 7You can use the args library to define and parse command-line arguments Functions as first-class objectsYou can pass a function as a parameter to another function. For example 8You can also assign a function to a variable, such as 9This example uses an anonymous function. More about those in the next section Anonymous functionsMost functions are named, such as 17 or 50. You can also create a nameless function called an anonymous function, or sometimes a lambda or closure. You might assign an anonymous function to a variable so that, for example, you can add or remove it from a collectionAn anonymous function looks similar to a named function—zero or more parameters, separated by commas and optional type annotations, between parentheses The code block that follows contains the function’s body 51The following example defines an anonymous function with an untyped parameter, 52, and passes it to the 53 function. The function, invoked for each item in the list, converts each string to uppercase. Then in the anonymous function passed to 54, each converted string is printed out alongside its length 0Click Run to execute the code 1Nếu hàm chỉ chứa một biểu thức hoặc câu lệnh trả về, bạn có thể rút gọn nó bằng cách sử dụng ký hiệu mũi tên. Dán dòng sau vào DartPad và nhấp vào Chạy để xác minh rằng nó có chức năng tương đương 2Lexical scopeDart is a lexically scoped language, which means that the scope of variables is determined statically, simply by the layout of the code. Bạn có thể “đi theo dấu ngoặc nhọn ra ngoài” để xem một biến có nằm trong phạm vi không Here is an example of nested functions with variables at each scope level 3Notice how 55 can use variables from every level, all the way up to the top levelĐóng từ vựngBao đóng là một đối tượng hàm có quyền truy cập vào các biến trong phạm vi từ vựng của nó, ngay cả khi hàm được sử dụng bên ngoài phạm vi ban đầu của nó Các chức năng có thể đóng trên các biến được xác định trong phạm vi xung quanh. Trong ví dụ sau, 56 nắm bắt biến 57. Hàm được trả về đi đến đâu, nó ghi nhớ 57 4Các chức năng kiểm tra cho bình đẳngĐây là một ví dụ về kiểm tra các hàm cấp cao nhất, các phương thức tĩnh và các phương thức thể hiện cho sự bình đẳng 5Giá trị trả vềTất cả các chức năng trả về một giá trị. Nếu không có giá trị trả về nào được chỉ định, câu lệnh 59 được ngầm thêm vào thân hàm 6nhà điều hànhDart hỗ trợ các toán tử được hiển thị trong bảng sau. Bảng hiển thị tính kết hợp toán tử của Dart và từ cao nhất đến thấp nhất, là một xấp xỉ của các mối quan hệ toán tử của Dart. Bạn có thể thực hiện nhiều trong số này DescriptionOperatorAssociativityunary postfix 60 61 62 67 64 65 66 43Noneunary prefix 68 69 70 71 72 73 Nonemultiplicative 74 75 76 77Leftadditive 59 79Leftshift 46 47 48Leftbitwise AND 50Leftbitwise XOR 52Leftbitwise OR 51Leftrelational and type test 86 87 88 89 99 98 92Noneequality 58 94 Nonelogical AND 95Leftlogical OR . ĐúngCảnh báo. Bảng trước chỉ nên được sử dụng như một hướng dẫn hữu ích. Khái niệm về ưu tiên toán tử và tính kết hợp là một xấp xỉ của sự thật được tìm thấy trong ngữ pháp ngôn ngữ. Bạn có thể tìm thấy hành vi có thẩm quyền của các mối quan hệ toán tử của Dart trong ngữ pháp được xác định trong đặc tả ngôn ngữ Dart Khi bạn sử dụng toán tử, bạn tạo biểu thức. Dưới đây là một số ví dụ về biểu thức toán tử 7Trong , mỗi toán tử có mức độ ưu tiên cao hơn các toán tử trong các hàng theo sau nó. Ví dụ: toán tử nhân 76 có mức độ ưu tiên cao hơn (và do đó thực thi trước) toán tử đẳng thức 58, có mức độ ưu tiên cao hơn toán tử logic AND 95. Quyền ưu tiên đó có nghĩa là hai dòng mã sau thực thi theo cùng một cách 8Cảnh báo. Đối với các toán tử nhận hai toán hạng, toán hạng ngoài cùng bên trái sẽ xác định phương thức nào được sử dụng. Ví dụ: nếu bạn có một đối tượng 11 và một đối tượng 12, thì 13 sử dụng phép cộng 11 ( 59)toán tử số họcDart hỗ trợ các toán tử số học thông thường, như trong bảng sau Toán tửÝ nghĩa_______58_______59Cộng 79Trừ 68Dấu trừ đơn vị hay còn gọi là phủ định (đảo dấu của biểu thức) 74Nhân 75Chia số 77Chia hết, trả về kết quả là số nguyên 76Lấy phần dư của một phép chia số nguyên (mô-đun)Thí dụ 9Dart cũng hỗ trợ cả toán tử tăng và giảm tiền tố và hậu tố Toán tửÝ nghĩa 23 24 (giá trị biểu thức là 25) 26 24 (giá trị biểu thức là 28) 29 30 (giá trị biểu thức là 31) 32 30 (giá trị biểu thức là 28)Thí dụ 0Toán tử đẳng thức và quan hệBảng sau liệt kê ý nghĩa của đẳng thức và toán tử quan hệ Toán tửÝ nghĩa 58Bằng nhau; Để kiểm tra xem hai đối tượng x và y có đại diện cho cùng một thứ hay không, hãy sử dụng toán tử 58. (Trong trường hợp hiếm hoi mà bạn cần biết liệu hai đối tượng có phải là cùng một đối tượng hay không, hãy sử dụng hàmgiống hệt() để thay thế. ) Đây là cách hoạt động của toán tử 58
Đây là một ví dụ về cách sử dụng từng toán tử đẳng thức và quan hệ 1Người vận hành thử nghiệm loạiCác toán tử 99, 98 và 92 rất hữu ích để kiểm tra các loại trong thời gian chạyToán tửÝ nghĩa 99Typecast (cũng được sử dụng để chỉ định)_______1_______98True nếu đối tượng có loại được chỉ định 92True nếu đối tượng không có loại được chỉ địnhKết quả của 51 là đúng nếu 52 triển khai giao diện được chỉ định bởi 53. Ví dụ: 54 luôn đúngSử dụng toán tử 99 để chuyển một đối tượng sang một loại cụ thể khi và chỉ khi bạn chắc chắn rằng đối tượng thuộc loại đó. Thí dụ 2Nếu bạn không chắc chắn rằng đối tượng thuộc loại 53, hãy sử dụng 57 để kiểm tra loại trước khi sử dụng đối tượng 3Ghi chú. Mã không tương đương. Nếu 58 là null hoặc không phải là 59, thì ví dụ đầu tiên đưa ra một ngoại lệ; Toán tử gánNhư bạn đã thấy, bạn có thể gán giá trị bằng cách sử dụng toán tử 34. Để chỉ gán nếu biến được gán là null, hãy sử dụng toán tử 61 4Các toán tử gán phức hợp như 04 kết hợp một phép toán với một phép gán 34 02 65 66 07 04 03 70 06 72 05 74 75Đây là cách các toán tử gán phức hợp hoạt động Phép gán hợp chấtBiểu thức tương đươngCho toán tử op. 76 77Ví dụ. 78 79Ví dụ sau sử dụng toán tử gán và gán phức hợp 5Toán tử logicBạn có thể đảo ngược hoặc kết hợp các biểu thức boolean bằng các toán tử logic Toán tửÝ nghĩa 69đảo ngược biểu thức sau (thay đổi sai thành đúng và ngược lại) 96logic OR 95logic ANDĐây là một ví dụ về việc sử dụng các toán tử logic 6Toán tử bitwise và shiftBạn có thể thao tác từng bit số trong Dart. Thông thường, bạn sẽ sử dụng các toán tử dịch chuyển và bit này với các số nguyên Toán tử Ý nghĩa_______58_______50AND 51OR 52XOR 70Phần bù bit đơn vị (0 trở thành 1; 1 trở thành 0) 46Shift trái 47Shift phải 48Shift không dấu phảiĐây là một ví dụ về việc sử dụng toán tử bitwise và shift 7ghi chú phiên bản. Toán tử 48 (được gọi là ca ba hoặc ca không dấu) yêu cầu ít nhất 2. 14biểu thức điều kiệnPhi tiêu có hai toán tử cho phép bạn đánh giá chính xác các biểu thức có thể yêu cầu các câu lệnh 91Nếu điều kiện là đúng, đánh giá expr1 (và trả về giá trị của nó); . 92Nếu expr1 khác null, trả về giá trị của nó; Khi bạn cần gán giá trị dựa trên biểu thức boolean, hãy cân nhắc sử dụng 39 và 94 8Nếu biểu thức boolean kiểm tra null, hãy cân nhắc sử dụng 97 9Ví dụ trước có thể được viết ít nhất theo hai cách khác, nhưng không ngắn gọn bằng 0ký hiệu tầngCascades ( 99, 00) cho phép bạn thực hiện một chuỗi các thao tác trên cùng một đối tượng. Ngoài việc truy cập các thành viên cá thể, bạn cũng có thể gọi các phương thức cá thể trên cùng một đối tượng. Điều này thường giúp bạn tiết kiệm bước tạo một biến tạm thời và cho phép bạn viết mã linh hoạt hơnHãy xem xét đoạn mã sau 1Hàm tạo, 98, trả về một đối tượng 99. Mã tuân theo ký hiệu xếp tầng hoạt động trên đối tượng này, bỏ qua mọi giá trị có thể được trả vềVí dụ trước tương đương với mã này 2Nếu đối tượng mà tầng hoạt động trên đó có thể là null, thì hãy sử dụng tầng rút ngắn null ( 00) cho thao tác đầu tiên. Bắt đầu với 00 đảm bảo rằng không có hoạt động xếp tầng nào được thực hiện trên đối tượng null đó 3ghi chú phiên bản. Cú pháp 00 yêu cầu ít nhất 2. 12Mã trước tương đương với mã sau 4Bạn cũng có thể lồng thác. Ví dụ 5Hãy cẩn thận để xây dựng tầng của bạn trên một hàm trả về một đối tượng thực tế. Ví dụ: đoạn mã sau không thành công 6Cuộc gọi 03 trả về giá trị vô hiệu và bạn không thể tạo tầng trên 15Ghi chú. Nói một cách chính xác, ký hiệu “dấu chấm kép” cho các tầng không phải là toán tử. Nó chỉ là một phần của cú pháp Dart nhà khai thác khácBạn đã thấy hầu hết các toán tử còn lại trong các ví dụ khác OperatorNameÝ nghĩa 62Ứng dụng chức năngĐại diện cho một cuộc gọi chức năng 67Truy cập đăng kýĐại diện cho một cuộc gọi đến nhà điều hành 67 có thể ghi đè; . 08 chuyển int 09 đến 10 để truy cập phần tử tại chỉ mục 09 64Truy cập chỉ số con có điều kiệnGiống như 67, nhưng toán hạng ngoài cùng bên trái có thể là null; . 14 chuyển int 09 đến 10 để truy cập phần tử tại chỉ mục 09 trừ khi 10 là null (trong trường hợp đó biểu thức ước tính là null)_______61_______65Truy cập thành viên Đề cập đến một thuộc tính của một biểu thức; . 20 chọn thuộc tính 21 từ biểu thức 22_______61_______66Truy cập thành viên có điều kiệnGiống như 65, nhưng toán hạng ngoài cùng bên trái có thể là null; . 25 chọn thuộc tính 21 từ biểu thức 22 trừ khi 22 là null (trong trường hợp đó, giá trị của 25 là null) 43Null assertion operatorTruyền một biểu thức sang loại không thể null cơ bản của nó, đưa ra một ngoại lệ thời gian chạy nếu truyền không thành công; . 31 khẳng định 22 không phải là null và chọn thuộc tính 21, trừ khi 22 là null trong trường hợp đó, một ngoại lệ thời gian chạy được đưa raĐể biết thêm thông tin về các toán tử 65, 66 và 99, hãy xemBáo cáo luồng điều khiểnBạn có thể kiểm soát luồng mã Dart của mình bằng cách sử dụng bất kỳ cách nào sau đây
Bạn cũng có thể tác động đến luồng điều khiển bằng cách sử dụng 49 và 50, như được giải thích trongNếu và khácDart hỗ trợ 00 câu lệnh với tùy chọn 39 câu lệnh, như mẫu tiếp theo cho thấy. Cũng thấy 7Các điều kiện câu lệnh phải là các biểu thức đánh giá các giá trị boolean, không có gì khác. Xem để biết thêm thông tin Đối với vòng lặpBạn có thể lặp với vòng lặp 79 tiêu chuẩn. Ví dụ 8Các lần đóng bên trong các vòng lặp 79 của Dart ghi lại giá trị của chỉ mục, tránh một cạm bẫy phổ biến được tìm thấy trong JavaScript. Ví dụ, xem xét 9Đầu ra là 55 và sau đó là 09, như mong đợi. Ngược lại, ví dụ sẽ in 57 và sau đó là 57 trong JavaScriptNếu đối tượng mà bạn đang lặp lại là một Có thể lặp lại (chẳng hạn như Danh sách hoặc Bộ) và nếu bạn không cần biết bộ đếm lặp lại hiện tại, bạn có thể sử dụng biểu mẫu 59 của 00Mẹo. Để thực hành sử dụng 59, hãy làm theo phòng thí nghiệm codelab bộ sưu tập IterableCác lớp có thể lặp lại cũng có một phương thức forEach() như một tùy chọn khác 01Trong khi và làm trong khiVòng lặp 41 đánh giá điều kiện trước vòng lặp 02Vòng lặp 42- 41 đánh giá điều kiện sau vòng lặp 03Phá vỡ và tiếp tụcSử dụng 44 để dừng vòng lặp 04Sử dụng 45 để chuyển sang vòng lặp tiếp theo 05Bạn có thể viết ví dụ đó theo cách khác nếu bạn đang sử dụng một 26 chẳng hạn như danh sách hoặc tập hợp 06Chuyển đổi và trường hợpChuyển câu lệnh trong Dart so sánh các hằng số nguyên, chuỗi hoặc thời gian biên dịch bằng cách sử dụng 58. Tất cả các đối tượng được so sánh phải là các thể hiện của cùng một lớp (và không thuộc bất kỳ kiểu con nào của nó) và lớp không được ghi đè lên 58. hoạt động tốt trong các câu lệnh 46Mỗi mệnh đề 47 không trống kết thúc bằng câu lệnh 44, theo quy định. Các cách hợp lệ khác để kết thúc mệnh đề 47 không trống là câu lệnh 45, 50 hoặc 75Sử dụng mệnh đề 76 để thực thi mã khi không có mệnh đề 47 khớp 07Ví dụ sau bỏ qua câu lệnh 44 trong mệnh đề 47, do đó tạo ra lỗi 08Tuy nhiên, Dart hỗ trợ các mệnh đề 47 trống rỗng, cho phép một hình thức rút gọn 09Nếu bạn thực sự muốn bỏ qua, bạn có thể sử dụng câu lệnh 45 và nhãn 10Mệnh đề 47 có thể có các biến cục bộ, chỉ hiển thị bên trong phạm vi của mệnh đề đókhẳng địnhTrong quá trình phát triển, hãy sử dụng câu lệnh khẳng định—______67_______83;—để phá vỡ quá trình thực thi bình thường nếu điều kiện boolean là sai. Bạn có thể tìm thấy các ví dụ về tuyên bố khẳng định trong chuyến tham quan này. Dưới đây là một số chi tiết 11Để đính kèm một thông báo vào một xác nhận, hãy thêm một chuỗi làm đối số thứ hai vào 48 (tùy chọn với một ) 12Đối số đầu tiên của 48 có thể là bất kỳ biểu thức nào phân giải thành giá trị boolean. Nếu giá trị của biểu thức là đúng, xác nhận thành công và quá trình thực thi tiếp tục. Nếu nó sai, khẳng định không thành công và một ngoại lệ (một 86) được đưa raKhi nào xác nhận chính xác hoạt động?
Trong mã sản xuất, các xác nhận bị bỏ qua và các đối số của 48 không được đánh giángoại lệMã phi tiêu của bạn có thể ném và bắt ngoại lệ. Ngoại lệ là lỗi cho biết có điều gì đó không mong muốn đã xảy ra. Nếu ngoại lệ không bị bắt, thì ngoại lệ đã đưa ra sẽ bị tạm dừng và thường thì cô lập và chương trình của nó bị chấm dứt Trái ngược với Java, tất cả các ngoại lệ của Dart đều là ngoại lệ không được kiểm tra. Các phương thức không khai báo những ngoại lệ mà chúng có thể ném ra và bạn không bắt buộc phải bắt bất kỳ ngoại lệ nào Phi tiêu cung cấp các loại 92 và 93, cũng như nhiều loại phụ được xác định trước. Tất nhiên, bạn có thể xác định các ngoại lệ của riêng mình. Tuy nhiên, các chương trình Dart có thể ném bất kỳ đối tượng không null nào—không chỉ các đối tượng Ngoại lệ và Lỗi—như một ngoại lệNémĐây là một ví dụ về ném hoặc nâng cao, một ngoại lệ 13Bạn cũng có thể ném các đối tượng tùy ý 14Ghi chú. Mã chất lượng sản xuất thường đưa ra các loại triển khai 93 hoặc 92Vì ném ngoại lệ là một biểu thức nên bạn có thể ném ngoại lệ vào câu lệnh => cũng như bất kỳ nơi nào khác cho phép biểu thức 15Bắt lấyBắt hoặc chụp, một ngoại lệ ngăn ngoại lệ lan truyền (trừ khi bạn vẽ lại ngoại lệ). Bắt một ngoại lệ cho bạn cơ hội để xử lý nó 16Để xử lý mã có thể ném nhiều loại ngoại lệ, bạn có thể chỉ định nhiều mệnh đề bắt. Mệnh đề bắt đầu tiên khớp với loại đối tượng bị ném sẽ xử lý ngoại lệ. Nếu mệnh đề catch không chỉ định một loại, thì mệnh đề đó có thể xử lý bất kỳ loại đối tượng bị ném nào 17Như đoạn mã trước cho thấy, bạn có thể sử dụng 96 hoặc 97 hoặc cả hai. Sử dụng 96 khi bạn cần chỉ định loại ngoại lệ. Sử dụng 97 khi trình xử lý ngoại lệ của bạn cần đối tượng ngoại lệBạn có thể chỉ định một hoặc hai tham số cho 00. Đầu tiên là ngoại lệ đã được ném và thứ hai là dấu vết ngăn xếp (đối tượng 01) 18Để xử lý một phần ngoại lệ, đồng thời cho phép nó lan truyền, hãy sử dụng từ khóa 02 19Cuối cùngĐể đảm bảo rằng một số mã chạy cho dù có ném ngoại lệ hay không, hãy sử dụng mệnh đề 03. Nếu không có mệnh đề 97 khớp với ngoại lệ, thì ngoại lệ sẽ được lan truyền sau khi mệnh đề 03 chạy 20Mệnh đề 03 chạy sau bất kỳ mệnh đề 97 phù hợp nào 21Tìm hiểu thêm bằng cách đọc phần tham quan thư viện Các lớp họcDart là một ngôn ngữ hướng đối tượng với các lớp và kế thừa dựa trên mixin. Mỗi đối tượng là một thể hiện của một lớp và tất cả các lớp ngoại trừ 17 đều giảm dần từ 35. Kế thừa dựa trên mixin có nghĩa là mặc dù mọi lớp (ngoại trừ , 45) có chính xác một lớp cha, nhưng phần thân của lớp có thể được sử dụng lại trong nhiều hệ thống phân cấp lớp. là một cách để thêm chức năng vào một lớp mà không cần thay đổi lớp hoặc tạo một lớp conSử dụng các thành viên lớpCác đối tượng có các thành viên bao gồm các hàm và dữ liệu (tương ứng là các phương thức và biến thể hiện). Khi bạn gọi một phương thức, bạn gọi nó trên một đối tượng. phương thức có quyền truy cập vào các chức năng và dữ liệu của đối tượng đó Sử dụng dấu chấm ( 65) để chỉ một biến thể hiện hoặc một phương thức 22Sử dụng 66 thay vì 65 để tránh ngoại lệ khi toán hạng ngoài cùng bên trái là null 23Sử dụng hàm tạoYou can create an object using a constructor. Constructor names can be either 14 or 15. For example, the following code creates 12 objects using the 17 and 18 constructors 24The following code has the same effect, but uses the optional 07 keyword before the constructor name 25Some classes provide . To create a compile-time constant using a constant constructor, put the 84 keyword before the constructor name 26Constructing two identical compile-time constants results in a single, canonical instance 27Within a constant context, you can omit the 84 before a constructor or literal. For example, look at this code, which creates a const map 28You can omit all but the first use of the 84 keyword 29If a constant constructor is outside of a constant context and is invoked without 84, it creates a non-constant object 30Getting an object’s typeTo get an object’s type at runtime, you can use the 35 property 25, which returns a 26 object 31Use a rather than 25 to test an object’s type. In production environments, the test 28 is more stable than the test 29Up to here, you’ve seen how to use classes. The rest of this section shows how to implement classes Instance variablesHere’s how you declare instance variables 32All uninitialized instance variables have the value 33All instance variables generate an implicit getter method. Non-final instance variables and 31 instance variables without initializers also generate an implicit setter method. For details, see If you initialize a non- 76 instance variable where it’s declared, the value is set when the instance is created, which is before the constructor and its initializer list execute 33Instance variables can be 83, in which case they must be set exactly once. Initialize 83, non- 76 instance variables at declaration, using a constructor parameter, or using a constructor’s 34If you need to assign the value of a 83 instance variable after the constructor body starts, you can use one of the following
ConstructorsDeclare a constructor by creating a function with the same name as its class (plus, optionally, an additional identifier as described in ). The most common form of constructor, the generative constructor, creates a new instance of a class 35The 80 keyword refers to the current instanceNote. Use 80 only when there is a name conflict. Otherwise, Dart style omits the 80Initializing formal parametersThe pattern of assigning a constructor argument to an instance variable is so common, Dart has initializing formal parameters to make it easy Initializing parameters can also be used to initialize non-nullable or 83 instance variables, which both must be initialized or provided a default value 36The variables introduced by the initializing formals are implicitly final and only in scope of the initializer list Default constructorsIf you don’t declare a constructor, a default constructor is provided for you. The default constructor has no arguments and invokes the no-argument constructor in the superclass Constructors aren’t inheritedSubclasses don’t inherit constructors from their superclass. A subclass that declares no constructors has only the default (no argument, no name) constructor Named constructorsUse a named constructor to implement multiple constructors for a class or to provide extra clarity 37Remember that constructors are not inherited, which means that a superclass’s named constructor is not inherited by a subclass. If you want a subclass to be created with a named constructor defined in the superclass, you must implement that constructor in the subclass Invoking a non-default superclass constructorBy default, a constructor in a subclass calls the superclass’s unnamed, no-argument constructor. The superclass’s constructor is called at the beginning of the constructor body. If an is also being used, it executes before the superclass is called. In summary, the order of execution is as follows
If the superclass doesn’t have an unnamed, no-argument constructor, then you must manually call one of the constructors in the superclass. Specify the superclass constructor after a colon ( 94), just before the constructor body (if any)In the following example, the constructor for the Employee class calls the named constructor for its superclass, Person. Click Run to execute the code 38Because the arguments to the superclass constructor are evaluated before invoking the constructor, an argument can be an expression such as a function call 39Warning. Arguments to the superclass constructor don’t have access to 80. For example, arguments can call static methods but not instance methodsTo avoid having to manually pass each parameter into the super invocation of a constructor, you can use super-initializer parameters to forward parameters to the specified or default superclass constructor. This feature can’t be used with redirecting constructors. Super-initializer parameters have similar syntax and semantics to 40Super-initializer parameters cannot be positional if the super-constructor invocation already has positional arguments, but they can always be named 41Version note. Using super-initializer parameters requires a of at least 2. 17. If you’re using an earlier language version, you must manually pass in all super constructor parameters Initializer listBesides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas 42Warning. The right-hand side of an initializer doesn’t have access to 80During development, you can validate inputs by using 48 in the initializer list 43Initializer lists are handy when setting up final fields. The following example initializes three final fields in an initializer list. Click Run to execute the code 44Redirecting constructorsSometimes a constructor’s only purpose is to redirect to another constructor in the same class. A redirecting constructor’s body is empty, with the constructor call (using 80 instead of the class name) appearing after a colon (. ) 45Constant constructorsIf your class produces objects that never change, you can make these objects compile-time constants. To do this, define a 84 constructor and make sure that all instance variables are 83 46Constant constructors don’t always create constants. For details, see the section on Factory constructorsUse the 50 keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype. Another use case for factory constructors is initializing a final variable using logic that can’t be handled in the initializer listTip. Another way to handle late initialization of a final variable is to In the following example, the 52 factory constructor returns objects from a cache, and the 53 factory constructor initializes a final variable from a JSON object 47Ghi chú. Các nhà xây dựng nhà máy không có quyền truy cập vào 80Gọi một nhà xây dựng nhà máy giống như bất kỳ nhà xây dựng nào khác 48phương phápPhương thức là các chức năng cung cấp hành vi cho một đối tượng Phương thức sơ thẩmCác phương thức thể hiện trên các đối tượng có thể truy cập các biến thể hiện và 80. Phương thức 56 trong mẫu sau đây là một ví dụ về phương thức thể hiện 49nhà điều hànhToán tử là các phương thức cá thể có tên đặc biệt. Phi tiêu cho phép bạn xác định toán tử với các tên sau 89 59 51 48 87 75 52 67 88 77 50 08 86 74 46 49 79 76 47 58Ghi chú. You may have noticed that some , like 94, aren’t in the list of names. That’s because they’re just syntactic sugar. For example, the expression 78 is syntactic sugar for 79An operator declaration is identified using the built-in identifier 80. The following example defines vector addition ( 59), subtraction ( 79), and equality ( 58) 50Getters and settersGetters and setters are special methods that provide read and write access to an object’s properties. Recall that each instance variable has an implicit getter, plus a setter if appropriate. You can create additional properties by implementing getters and setters, using the 84 and 85 keywords 51With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code Note. Operators such as increment (++) work in the expected way, whether or not a getter is explicitly defined. To avoid any unexpected side effects, the operator calls the getter exactly once, saving its value in a temporary variable Abstract methodsInstance, getter, and setter methods can be abstract, defining an interface but leaving its implementation up to other classes. Abstract methods can only exist in To make a method abstract, use a semicolon (;) instead of a method body 52Abstract classesUse the 86 modifier to define an abstract class—a class that can’t be instantiated. Abstract classes are useful for defining interfaces, often with some implementation. If you want your abstract class to appear to be instantiable, define a Abstract classes often have . Here’s an example of declaring an abstract class that has an abstract method 53Implicit interfacesEvery class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface A class implements one or more interfaces by declaring them in an 87 clause and then providing the APIs required by the interfaces. For example 54Here’s an example of specifying that a class implements multiple interfaces 55Extending a classUse 88 to create a subclass, and 89 to refer to the superclass 56For another usage of 88, see the discussion of in Overriding membersSubclasses can override instance methods (including ), getters, and setters. You can use the 91 annotation to indicate that you are intentionally overriding a member 57An overriding method declaration must match the method (or methods) that it overrides in several ways
Sometimes you might want to narrow the type of a method parameter or an instance variable. This violates the normal rules, and it’s similar to a downcast in that it can cause a type error at runtime. Still, narrowing the type is possible if the code can guarantee that a type error won’t occur. In this case, you can use the in a parameter declaration. For details, see the Dart language specification Warning. If you override 58, you should also override Object’s 98 getter. For an example of overriding 58 and 98, see noSuchMethod()To detect or react whenever code attempts to use a non-existent method or instance variable, you can override 01 58You can’t invoke an unimplemented method unless one of the following is true
For more information, see the informal noSuchMethod forwarding specification Extension methodsExtension methods are a way to add functionality to existing libraries. You might use extension methods without even knowing it. For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods Here’s an example of using an extension method on 20 named 06 that’s defined in 07 59For details of using and implementing extension methods, see the extension methods page Enumerated typesEnumerated types, often called enumerations or enums, are a special kind of class used to represent a fixed number of constant values Note. All enums automatically extend the 23 class. They are also sealed, meaning they cannot be subclassed, implemented, mixed in, or otherwise explicitly instantiatedAbstract classes and mixins can explicitly implement or extend 23, but unless they are then implemented by or mixed into an enum declaration, no objects can actually implement the type of that class or mixinDeclaring simple enumsTo declare a simple enumerated type, use the 10 keyword and list the values you want to be enumerated 60Tip. You can also use when declaring an enumerated type to help prevent copy-paste errors Declaring enhanced enumsDart also allows enum declarations to declare classes with fields, methods, and const constructors which are limited to a fixed number of known constant instances To declare an enhanced enum, follow a syntax similar to normal , but with a few extra requirements
Here is an example that declares an enhanced enum with multiple instances, instance variables, a getter, and an implemented interface 61To learn more about declaring enhanced enums, see the section on Version note. Enhanced enums require a of at least 2. 17 Using enumsAccess the enumerated values like any other 62Each value in an enum has an 13 getter, which returns the zero-based position of the value in the enum declaration. For example, the first value has index 0, and the second value has index 1 63To get a list of all the enumerated values, use the enum’s 16 constant 64You can use enums in , and you’ll get a warning if you don’t handle all of the enum’s values 65If you need to access the name of an enumerated value, such as 20 from 21, use the 22 property 66Thêm các tính năng cho một lớp. hỗn hợpMixin là một cách sử dụng lại mã của một lớp trong nhiều hệ thống phân cấp lớp Để sử dụng mixin, hãy sử dụng từ khóa 23 theo sau là một hoặc nhiều tên mixin. Ví dụ sau đây cho thấy hai lớp sử dụng mixins 67To implement a mixin, create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the 24 keyword instead of 25. For example 68Sometimes you might want to restrict the types that can use a mixin. For example, the mixin might depend on being able to invoke a method that the mixin doesn’t define. As the following example shows, you can restrict a mixin’s use by using the 96 keyword to specify the required superclass 69In the preceding code, only classes that extend or implement the 27 class can use the mixin 28. Because 29 extends 27, 29 can mix in 28Class variables and methodsUse the 33 keyword to implement class-wide variables and methodsStatic variablesStatic variables (class variables) are useful for class-wide state and constants 70Static variables aren’t initialized until they’re used Note. This page follows the of preferring 34 for constant namesStatic methodsStatic methods (class methods) don’t operate on an instance, and thus don’t have access to 80. They do, however, have access to static variables. As the following example shows, you invoke static methods directly on a class 71Note. Consider using top-level functions, instead of static methods, for common or widely used utilities and functionality You can use static methods as compile-time constants. For example, you can pass a static method as a parameter to a constant constructor GenericsIf you look at the API documentation for the basic array type, 21, you’ll see that the type is actually 37. The <…> notation marks List as a generic (or parameterized) type—a type that has formal type parameters. , most type variables have single-letter names, such as E, T, S, K, and V.Why use generics?Generics are often required for type safety, but they have more benefits than just allowing your code to run
If you intend for a list to contain only strings, you can declare it as 46 (read that as “list of string”). That way you, your fellow programmers, and your tools can detect that assigning a non-string to the list is probably a mistake. Here’s an example 72Another reason for using generics is to reduce code duplication. Generics let you share a single interface and implementation between many types, while still taking advantage of static analysis. For example, say you create an interface for caching an object 73You discover that you want a string-specific version of this interface, so you create another interface 74Later, you decide you want a number-specific version of this interface… You get the idea Generic types can save you the trouble of creating all these interfaces. Instead, you can create a single interface that takes a type parameter 75In this code, T is the stand-in type. It’s a placeholder that you can think of as a type that a developer will define later Using collection literalsList, set, and map literals can be parameterized. Parameterized literals are just like the literals you’ve already seen, except that you add 39 (for lists and sets) or 40 (for maps) before the opening bracket. Here is an example of using typed literals 76Using parameterized types with constructorsTo specify one or more types when using a constructor, put the types in angle brackets ( 41) just after the class name. For example 77Đoạn mã sau tạo một bản đồ có các khóa và giá trị số nguyên thuộc loại Chế độ xem 78Generic collections and the types they containDart generic types are reified, which means that they carry their type information around at runtime. For example, you can test the type of a collection 79Note. In contrast, generics in Java use erasure, which means that generic type parameters are removed at runtime. In Java, you can test whether an object is a List, but you can’t test whether it’s a 46Restricting the parameterized typeWhen implementing a generic type, you might want to limit the types that can be provided as arguments, so that the argument must be a subtype of a particular type. You can do this using 88A common use case is ensuring that a type is non-nullable by making it a subtype of 35 (instead of the default, ) 80You can use 88 with other types besides 35. Here’s an example of extending 48, so that members of 48 can be called on objects of type 53 81It’s OK to use 48 or any of its subtypes as the generic argument 82It’s also OK to specify no generic argument 83Specifying any non- 48 type results in an error 84Using generic methodsMethods and functions also allow type arguments 85Here the generic type parameter on 53 ( 54) allows you to use the type argument 53 in several places
Libraries and visibilityThe 59 and 60 directives can help you create a modular and shareable code base. Libraries not only provide APIs, but are a unit of privacy. identifiers that start with an underscore ( 54) are visible only inside the library. Every Dart app is a library, even if it doesn’t use a 60 directiveLibraries can be distributed using packages Nếu bạn muốn biết tại sao Dart lại sử dụng dấu gạch dưới thay vì các từ khóa bổ trợ truy cập như 51 hoặc 53, hãy xem vấn đề về SDK 33383Using librariesUse 59 to specify how a namespace from one library is used in the scope of another libraryFor example, Dart web apps generally use the dart. html library, which they can import like this 86The only required argument to 59 is a URI specifying the library. For built-in libraries, the URI has the special 67 scheme. For other libraries, you can use a file system path or the 68 scheme. The 68 scheme specifies libraries provided by a package manager such as the pub tool. Ví dụ 87Note. URI stands for uniform resource identifier. URLs (uniform resource locators) are a common kind of URI Specifying a library prefixIf you import two libraries that have conflicting identifiers, then you can specify a prefix for one or both libraries. For example, if library1 and library2 both have an Element class, then you might have code like this 88Importing only part of a libraryIf you want to use only part of a library, you can selectively import the library. For example 89Lazily loading a libraryDeferred loading (also called lazy loading) allows a web app to load a library on demand, if and when the library is needed. Here are some cases when you might use deferred loading
Only 89 supports deferred loading. Flutter and the Dart VM don’t support deferred loading. To learn more, see issue #33118 and issue #27776To lazily load a library, you must first import it using 71 90When you need the library, invoke 72 using the library’s identifier 91In the preceding code, the 59 keyword pauses execution until the library is loaded. For more information about 61 and 59, see You can invoke 72 multiple times on a library without problems. The library is loaded only onceKeep in mind the following when you use deferred loading
Implementing librariesSee Create Library Packages for advice on how to implement a library package, including
Asynchrony supportDart libraries are full of functions that return 24 or 25 objects. These functions are asynchronous. they return after setting up a possibly time-consuming operation (such as I/O), without waiting for that operation to completeThe 61 and 59 keywords support asynchronous programming, letting you write asynchronous code that looks similar to synchronous codeHandling FuturesWhen you need the result of a completed Future, you have two options
Code that uses 61 and 59 is asynchronous, but it looks a lot like synchronous code. For example, here’s some code that uses 59 to wait for the result of an asynchronous function 92To use 59, code must be in an 61 function—a function marked as 61 93Note. Although an 61 function might perform time-consuming operations, it doesn’t wait for those operations. Instead, the 61 function executes only until it encounters its first 59 expression. Then it returns a 24 object, resuming execution only after the 59 expression completesUse 01, 97, and 03 to handle errors and cleanup in code that uses 59 94You can use 59 multiple times in an 61 function. For example, the following code waits three times for the results of functions 95In 07, the value of 08 is usually a Future; if it isn’t, then the value is automatically wrapped in a Future. This Future object indicates a promise to return an object. The value of 07 is that returned object. The await expression makes execution pause until that object is availableIf you get a compile-time error when using 59, make sure 59 is in an 61 function. For example, to use 59 in your app’s 17 function, the body of 17 must be marked as 61 96Note. The preceding example uses an 61 function ( 18) without waiting for a result—a practice that can cause problems if the code assumes that the function has finished executing. To avoid this problem, use the For an interactive introduction to using futures, 61, and 59, see the asynchronous programming codelabDeclaring async functionsAn 61 function is a function whose body is marked with the 61 modifierAdding the 61 keyword to a function makes it return a Future. For example, consider this synchronous function, which returns a String 97If you change it to be an 61 function—for example, because a future implementation will be time consuming—the returned value is a Future 98Note that the function’s body doesn’t need to use the Future API. Dart creates the Future object if necessary. If your function doesn’t return a useful value, make its return type 25For an interactive introduction to using futures, 61, and 59, see the asynchronous programming codelabHandling StreamsWhen you need to get values from a Stream, you have two options
Note. Before using 29, be sure that it makes the code clearer and that you really do want to wait for all of the stream’s results. For example, you usually should not use 29 for UI event listeners, because UI frameworks send endless streams of eventsAn asynchronous for loop has the following form 99The value of 08 must have type Stream. Execution proceeds as follows
To stop listening to the stream, you can use a 44 or 75 statement, which breaks out of the for loop and unsubscribes from the streamIf you get a compile-time error when implementing an asynchronous for loop, make sure the 29 is in an 61 function. For example, to use an asynchronous for loop in your app’s 17 function, the body of 17 must be marked as 61 00For more information about asynchronous programming, in general, see the section of the library tour GeneratorsWhen you need to lazily produce a sequence of values, consider using a generator function. Dart có hỗ trợ tích hợp cho hai loại hàm tạo
To implement a synchronous generator function, mark the function body as 63, and use 60 statements to deliver values 01To implement an asynchronous generator function, mark the function body as 62, and use 60 statements to deliver values 02If your generator is recursive, you can improve its performance by using 46 03các lớp có thể gọi đượcTo allow an instance of your Dart class to be called like a function, implement the 47 methodPhương thức 47 cho phép bất kỳ lớp nào định nghĩa nó mô phỏng một hàm. Phương thức này hỗ trợ các chức năng giống như bình thường, chẳng hạn như tham số và kiểu trả vềTrong ví dụ sau, lớp 49 định nghĩa một hàm 47 nhận ba chuỗi và nối chúng lại, tách từng chuỗi bằng dấu cách và thêm một dấu chấm than. Nhấp vào Chạy để thực thi mã 04cô lậpHầu hết các máy tính, ngay cả trên nền tảng di động, đều có CPU đa lõi. Để tận dụng tất cả các lõi đó, theo truyền thống, các nhà phát triển sử dụng các luồng bộ nhớ dùng chung chạy đồng thời. Tuy nhiên, đồng thời trạng thái chia sẻ dễ bị lỗi và có thể dẫn đến mã phức tạp Thay vì các luồng, tất cả mã Dart chạy bên trong các phân lập. Mỗi cô lập Dart sử dụng một luồng thực thi duy nhất và không chia sẻ các đối tượng có thể thay đổi với các cô lập khác. Quay nhiều cô lập tạo ra nhiều luồng thực thi. This enables multi-threading without its primary drawback, For more information, see the following
TypedefsA type alias—often called a typedef because it’s declared with the keyword 51—is a concise way to refer to a type. Here’s an example of declaring and using a type alias named 52 05A type alias can have type parameters 06Version note. Before 2. 13, typedefs were restricted to function types. Using the new typedefs requires a of at least 2. 13 We recommend using instead of typedefs for functions, in most situations. However, function typedefs can still be useful 07MetadataUse metadata to give additional information about your code. Chú thích siêu dữ liệu bắt đầu bằng ký tự 53, theo sau là tham chiếu đến hằng số thời gian biên dịch (chẳng hạn như 54) hoặc gọi hàm tạo hằng sốThree annotations are available to all Dart code. 55, 56, and 91. For examples of using 91, see . Here’s an example of using the 55 annotation 08You can define your own metadata annotations. Here’s an example of defining a 60 annotation that takes two arguments 09And here’s an example of using that 60 annotation 10Metadata can appear before a library, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import or export directive. You can retrieve metadata at runtime using reflection CommentsDart supports single-line comments, multi-line comments, and documentation comments Single-line commentsA single-line comment begins with 62. Mọi thứ giữa 62 và cuối dòng đều bị trình biên dịch Dart bỏ qua 11Nhận xét nhiều dòngChú thích nhiều dòng bắt đầu bằng 64 và kết thúc bằng 65. Mọi thứ giữa 64 và 65 đều bị trình biên dịch Dart bỏ qua (trừ khi nhận xét là nhận xét tài liệu; xem phần tiếp theo). Nhận xét nhiều dòng có thể lồng vào nhau 12Nhận xét tài liệuNhận xét tài liệu là nhận xét nhiều dòng hoặc một dòng bắt đầu bằng 68 hoặc 69. Sử dụng 68 trên các dòng liên tiếp có tác dụng tương tự như nhận xét tài liệu nhiều dòngBên trong một nhận xét tài liệu, bộ phân tích bỏ qua tất cả văn bản trừ khi nó được đặt trong ngoặc đơn. Sử dụng dấu ngoặc, bạn có thể tham chiếu đến các lớp, phương thức, trường, biến cấp cao nhất, hàm và tham số. Tên trong ngoặc được giải quyết trong phạm vi từ vựng của phần tử chương trình được ghi lại Dưới đây là một ví dụ về nhận xét tài liệu có tham chiếu đến các lớp và đối số khác 13Trong tài liệu do lớp tạo ra, 71 trở thành liên kết đến tài liệu cho phương pháp 72 và 73 trở thành liên kết đến tài liệu cho lớp 74Để phân tích mã Dart và tạo tài liệu HTML, bạn có thể sử dụng công cụ tạo tài liệu của Dart, 75. Để biết ví dụ về tài liệu được tạo, hãy xem tài liệu API Dart. Để được tư vấn về cách cấu trúc nhận xét của bạn, hãy xem Phi tiêu hiệu quả. Tài liệuSummaryThis page summarized the commonly used features in the Dart language. Nhiều tính năng đang được triển khai, nhưng chúng tôi hy vọng rằng chúng sẽ không phá vỡ mã hiện có. Để biết thêm thông tin, hãy xem Đặc tả ngôn ngữ phi tiêu và Phi tiêu hiệu quả Hàm ẩn danh trong PHP là gì?Hàm ẩn danh, còn được gọi là bao đóng, cho phép tạo các hàm không có tên cụ thể . Chúng hữu ích nhất với vai trò là giá trị của các tham số có thể gọi được, nhưng chúng cũng có nhiều cách sử dụng khác. Các hàm ẩn danh được triển khai bằng lớp Đóng.
Chức năng ẩn danh dùng để làm gì?Hàm ẩn danh là một hàm không được lưu trữ trong tệp chương trình, nhưng được liên kết với một biến có kiểu dữ liệu là function_handle. Các hàm ẩn danh có thể chấp nhận nhiều đầu vào và trả về một đầu ra . Chúng chỉ có thể chứa một câu lệnh thực thi duy nhất.
Hai cách sử dụng phổ biến của các chức năng ẩn danh là gì?Chúng ta có thể sử dụng hàm ẩn danh trong JavaScript cho một số mục đích. Một số trong số họ được đưa ra dưới đây. Truyền hàm ẩn danh cho hàm khác làm đối số . Chúng ta cũng có thể sử dụng một hàm ẩn danh làm đối số cho một hàm khác.
Tại sao lại sử dụng hàm ẩn danh trong go?Hàm ẩn danh là một hàm không chứa bất kỳ tên nào. It is useful when you want to create an inline function . Trong ngôn ngữ Go, một hàm ẩn danh có thể tạo thành một bao đóng. Một chức năng ẩn danh còn được gọi là chức năng chữ. |