For those who were new to Python as a programming language, we've summarized Dart's grammar. I focused only on the differences from Python. I am aiming for a level where I can understand the code of flutter's simple app.
If you have any mistakes, feel free to comment!
In dart you absolutely must define a function named main
in the file. This is because it is automatically called first when the file is executed. Since the program is written like ... by calling another function from the main function, basically all the processing is written in the function. (Of course, class variables can be defined outside the function.
Python is dynamically typed, but Dart supports both dynamic and static typing. Static typing is to specify in the code the type of the object that will be included in the variable or return value. Dynamic typing is the opposite.
** In the following explanation, the main function is omitted for the sake of simplicity. ** **
Basically you need to write a semicolon at the end of the line.
print("hoge");
Write the unit with {}
instead of indentation. It seems that you don't need a semicolon after the curly braces.
hoge(){
print("hoge");
}
// coment
/* hoge
hoge
hoge
*/
///document
///document
You need to define the variable using var
before making the assignment.
var hoge;
Definitions and assignments can also be written in one line.
var hoge = 0;
Instead of var
, it can be defined by specifying the type. In this case, the variable cannot be assigned as an object of that type.
int hoge = 0;
If you add one underscore at the beginning, it will be treated as private and you will not be able to access it from outside the class.
int _hoge = 2;
Like Python, assignment is "like pasting a name sticker". (Pass by reference) Therefore, Example phenomenon occurs. The specifications of Coco Rahen seem to be the same.
Constants can be defined using const
and final
. I summarized the difference between the two.
Qualification | Use properly(Personal view) | Description |
---|---|---|
final |
When not assigned at the same time as the definition. | It means "once you associate an object with a variable, the variable cannot be associated with any other object". However,final The value may not be assigned at the time of adding. In addition, changes that do not change the position of the memory area (such as changing array elements) are possible. |
const |
When substituting at the same time as the definition. | const In the case of, the change of the contents of the memory area is not allowed at all. In other words, it is impossible to change the elements of the array. It is necessary to substitute when you get a job. |
It is not necessary to add var
because it is used at the time of definition in the first place. It also includes the meaning of defining.
final hoge;
Of course, you can also specify the type.
const int hoge =0;
You can embed a variable in a string by writing the variable name after the dollar mark $
. If it is not a String type, it is automatically converted to a String type.
var hoge = 0;
print("hoge refers $hoge");
If you want to embed an expression instead of a variable, enclose the expression in curly braces.
print("1 + 1 = ${1 + 1}");
When converting from String type to int type, do as follows.
var one = int.parse('1');
When converting from int type to String type, do as follows. If you want to convert to embed in a string, use [Code above](# Embed variable in string).
String oneAsString = 1.toString();
There is no particular wording to declare the definition of the function.
hoge(int number){
return number;
}
You can declare the return type before the function name. Write as void
that does not return a return value.
int hoge(int number){
return number;
}
If there is only one line of processing in the function, you can write easy-to-read code using the arrow mark =>
. => Expression
is a simplified way of writing{return expression;}
.
void main() => print("hoge");
Formal arguments enclosed in curly braces can be passed by specifying the formal parameters. Named arguments are included in the optional argument category and can be omitted. If omitted, null
is returned. Unlike Python, you can only pass formal arguments with named arguments.
int hoge({int number}){
return number;
}
If you don't want to omit it, you can force it with @ required
. However, you need to import package: meta / meta.dart
to use this annotation.
int hoge({@required int number}){
return number;
}
When calling, use a colon :
to specify the argument.
hoge(name : "Mike");
I've summarized only the major operators that differ between Python and Dart.
Dart | Python |
---|---|
~/ | // |
++ | +=1 |
-- | -=1 |
&& | and |
|| | or |
??=
One of the assignment operators. Since it is common to have a specific operation when it is null, a convenient operator is provided. This operator performs assignment processing only when the left side is null.
int a;
a ??= 3;
Finally, 3 is substituted for a.
??
Similar to the operator above, but this is a class of expressions that return a value. Returns the right side when the left side is null.
int a;
print(a ?? 3)
3 is output to the console.
Basically, the condition needs to be put in ()
.
if
This is the only difference.
Dart | Python |
---|---|
else if |
elif |
bool value? Expression: Used in the form of expression
. Returns the expression to the left of the colon when the bool value is True, and returns the expression to the right when False.
var isPerson = true;
print(isPerson ? "Yes": "No");
In this case, Yes is output.
for
The condition part is written as (variable definition and assignment; continuation condition; continuation processing)
.
for (int number = 0; number < 3; number++){
print(number);
}
It also supports writing styles similar to Python code.
var numbers = [0, 1, 2];
for (var number in numbers) {
print(number);
}
switch
There are some things, but I didn't use it in Python, so I'll omit it for the time being.
import
In Python, specify the name of the package or module, but in Dart, specify the URI. Since URIs are strings, not identifiers, they are enclosed in single or double quotes. By the way, URI is an evolution of URL, and it is a notation created based on the idea of "Let's name everything like URL by using schemes other than http and https used in URL!" Method. The structure of the URI is [Scheme: Path]. [^ 1] The scheme when using a package is package
, and when using Dart's built-in library, it is dart
.
If you just want to read another dart file, enter the absolute path or relative path.
Statements that start with @
are called annotations and are used to assign specific properties to methods and the like. It's like a decorator in Python.
The difference between a class variable and an instance variable is whether or not to qualify with static
. When modified, it is treated as a class variable and can be treated as a variable common to the class. The place to define is directly under class for both class variables and instance variables. On the contrary, it cannot be defined except directly under the class.
If you have any doubts about Python classes [My work here](https://qiita.com/basashi/items/69fee6df0f23f140e91c#q3-%E3%82%AF%E3%83%A9%E3%82%B9% E5% A4% 89% E6% 95% B0% E3% 81% A8% E3% 82% A4% E3% 83% B3% E3% 82% B9% E3% 82% BF% E3% 83% B3% E3% 82% B9% E5% A4% 89% E6% 95% B0% E3% 81% AE% E9% 81% 95% E3% 81% 84).
class JapanesePerson{
static String nationality = "Japan"; //Class variables
int age; //Instance variables
String name; //Instance variables
}
this
Unlike Python, there is no need to give an instance to a method as an argument of self. In Dart this is a special variable that returns itself when used inside a method.
class Person{
String name;
void info(){
print("My name is ${this.name}");
}
}
Exactly the same name as the class
Return type is not specified
No return value
A method that satisfies all of the above is recognized as a constructor.
class Person{
String name;
Person(name){
this.name = name;
}
}
Various functions of the constructor below
If you pass an instance variable as an argument of the constructor, the assignment process will be performed automatically. It's exactly the same as the code above.
class Person {
String name;
Person(this.name);
}
There is no overload in Dart or Python (a function that defines a constructor with the same name and automatically uses it according to the number of variables). As an alternative, you can create multiple constructors with class name.arbitrary name ()
. However, when instantiating, it must be instantiated as a class name including its name.
class Person{
String name;
Person(name){
this.name = name;
}
Person.gest(){
this.name = "gest";
}
}
It is used when you want to instantiate an object whose variable value does not change. All nests should be constants and the constructor should be prefixed with const
.
class Hoge{
final name;
const Hoge(this.name);
}
By writing another constructor after the colon, you can call another constructor and baton touch the process. In this case, this is returning itself, that is, Person, so we are passing " gest "
to the Person constructor.
class Person{
String name;
Person(name){
this.name = name;
}
Person.gest(): this("gest");
}
In Python, the parent class is described in ()
, but in Dart, it is described after ʻextends`.
class Person{
int age;
String name;
}
class JapanesePerson extends Person{
static String nationality = "Japan";
}
super
super
returns the parent class. You can think that the super part is garbled in the class name, so if you do super ()
, you will call the constructor of the parent class.
The big difference from Python is that ** super
cannot be used in the constructor **. Use constructor redirects to avoid this.
When calling the constructor of the parent class, it looks like this. We also use Constructor Redirection (#Constructor Redirection) and Syntactic sugar (# syntactic-sugar convenient syntax).
class Person{
int age;
String name;
Person(this.age, this.name);
info (){
print("My name is ${this.name}.");
}
}
class JapanesePerson extends Person{
static String nationality = "Japan";
var prefecture;
JapanesePerson(age, name, this.prefecture): super(age, name);//Here
}
You need to add @override
as an annotation on the line above.
@override
info(){
print("hoge");
}
setter/getter
I'm still not sure. Will study. .. .. I don't see much in Flutter code.
assert()
If the expression passed to the argument is false
, an error will be issued. It seems to be used during development. This code is ignored except for debugging. I get an error with the following code.
var n = 3;
assert(n == 1);
Introduction to Dart 2 for beginners
About Dart constructor | Developers.IO
[^ 1]: It's the path part, but in the case of http, the beginning of the path is //
, right? This seems to be a rule only when the scheme is http.
Recommended Posts