2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactNative開発者のためのFlutter入門~文法編~

Posted at

こんにちは。普段ReactNativeでアプリケーションを開発しているMちゃんです!
前から良いと評判のFlutterをやってみたいなとずっと思ってたのですが、ようやく重い腰を上げてようやく取り組んだので、ReactNativeと比べてどうなのか?という視点も含めて書いていきたいと思います!

Flutterとは

FlutterはDartを開発言語としており、Googleによって開発されたモバイルアプリケーションSDK
ReactNativeと同じで1つのコードからiOS,Android両方のプラットフォームで動作するアプリケーションが作成できます。
独自のレンダリングエンジンを実装しており、Hot Reloadが魅力を1つです。

文法の違い

変数

ReactNativeは動的型付けです。
Dartでは静的、動的の2つを組み合わされています。
型は必須ですが、一部の型注釈は省略可能です。

// JavaScript
var name = 'Flutter';
// Dart
String name = 'Flutter';
var name = 'flutter';

既定値

ReactNative(JavaScript)の既定値はundefined。
Dartはnullになります。

// JavaScript
var name; // undefined
// Dart
String name; // null

if判定

ReactNative(JavaScript)ではifの条件0またはnullがfalse。
Dartではfalseのみです。

// JavaScript
var myNull = null;
if (!myNull) {
  console.log('null is treated as false');
}
var zero = 0;
if (!zero) {
  console.log('0 is treated as false');
}
// Dart
var myNull = null;
if (myNull == null) {
  print('use "== null" to check null');
}
var zero = 0;
if (zero == 0) {
  print('use "== 0" to check zero');
}

関数

Dartでは戻り値がvoidの時は省略して書きます。
また、functionという文字も不要です。

// JavaScript
function fn() {
  return true;
}
// Dart
fn() {
  return true;
}
// can also be written as
bool fn() {
  return true;
}

非同期処理

非同期処理においてコールバック関数は重要な要点です。
Dartにはアロー関数が存在しないので、少し書き方が異なりますが大まかには一緒です。

// JavaScript
fetch(url)
  .then(response => response.json())
  .then(responseJson => {
    const ip = responseJson.origin;
    return ip;
  });
// Dart
http.get(url).then((response) {
  String ip = jsonDecode(response.body)['origin'];
  return ip;
});

ただし、(ip) => print(ip)のように1行だけの関数はアロー関数のように書くことができます。

// Dart
final example = new Example();
example
  ._getIPAddress()
  .then((ip) => print(ip))
  .catchError((error) => print(error));

asyncとawait

JavaScriptとDartでは使用方法は基本的に同じですが、宣言する場所が若干違います。

// JavaScript
async function _getIPAddress() {
  const url = 'https://httpbin.org/ip';
  const response = await fetch(url);
  ...
}
// Dart
Future<String> _getIPAddress() async {
  final url = 'https://httpbin.org/ip';
  final response = await http.get(url);
  ...
}

感想

今回はDart文法を学習していきましたが、静的型付けが魅力の一つだなと思いました。
次回はFlutterについて本格的にやっていこうと思います!
次回もお楽しみに✨

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?