Dart grammar for those who only know Python

Introduction

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!

A big difference from Python

  1. 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.

  2. 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. ** **

Basic rules

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");
}

comment

// coment

/* hoge
hoge
hoge
*/

///document
///document

variable

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.

constant

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,finalThe 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. constIn 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;

Embedding variables in strings

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}");

Type conversion

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();

function

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");

Named arguments

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");

operator

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.

Control statement

Basically, the condition needs to be put in ().

if

This is the only difference.

Dart Python
else if elif

if-else alternative syntax

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.

Annotation (formerly loosen!)

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.

class

Class variables and instance variables

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}");
  }
}

constructor

  1. Exactly the same name as the class

  2. Return type is not specified

  3. 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

Syntactic sugar

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);
}

Named constructor

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";
  }
}

Constant constructor

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); 
}

Constructor redirect

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");
}

Inheritance

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
}

override

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);

Referenced site

Dart documentation | Dart

DartPad

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

Dart grammar for those who only know Python
For those who want to write Python with vim
For those who can't install Python on Windows XP
Basic Python grammar for beginners
[Python] Sample code for Python grammar
Extract only Python for preprocessing
For those who are having trouble drawing graphs in python
Minimum grammar notes for writing Python
Python environment construction 2016 for those who aim to be data scientists
Python techniques for those who want to get rid of beginners
A memo for those who use Python in Visual Studio (me)
AWS ~ For those who will use it ~
Introduced Mac (M1) TensorFlow (recommended for those who have installed python by themselves)
Tips for those who are wondering how to use is and == in Python
Join Azure Using Go ~ For those who want to start and know Azure with Go ~
For those who want to learn Excel VBA and get started with Python
[Solved] I have a question for those who are familiar with Python mechanize.
Things to keep in mind when using Python for those who use MATLAB
5 Reasons Processing is Useful for Those Who Want to Get Started with Python
Memo # 4 for Python beginners to read "Detailed Python Grammar"
Instant method grammar for Python and Ruby (studying)
For those who have done pip uninstall setuptools
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Memo # 1 for Python beginners to read "Detailed Python Grammar"
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Memo # 6 for Python beginners to read "Detailed Python Grammar"
Memo # 5 for Python beginners to read "Detailed Python Grammar"
Software training for those who start researching space
2016-10-30 else for Python3> for:
python [for myself]
python grammar check
The first step of machine learning ~ For those who want to implement with python ~
[For those who have mastered other programming languages] 10 points to catch up on Python points
Python grammar notes
Python3 basic grammar
❤️ Bloggers ❤️ "Beloved BI" ❤️ Let's get started ❤️ (For those who can make charts with Python)
For those who are new to programming but have decided to analyze data with Python
Environment construction for those who want to study python easily with VS Code (for Mac)
For those who should have installed janome properly with Python but get an error
Anxible points for those who want to introduce Ansible
[For beginners] Learn basic Python grammar for free in 5 hours!
For those who get Getting Key Error:'length_seconds' on pytube
ABC's A problem analysis for the past 15 times to send to those who are new to Python
For those who are in trouble because NFC is read infinitely when reading NFC with Python
Knowledge for those who are only thinking about running the Qore SDK on a Mac
Environment construction procedure for those who are not familiar with the python version control system