0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlutterでJavaScriptのモデルを定義してdartからメソッドを呼ぶ

Posted at

パッケージのインストール

  • jsパッケージ
  • freezedパッケージとその関連パッケージ

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  js:
  freezed_annotation: 
  json_annotation: 

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner:
  freezed: 
  json_serializable: 
  

今回使用するクラス

  • StorageManger

やりたいこと

dart側からfetchStorageEstimate()を呼ぶとjsのnavigator.storage.estimate()を呼ぶ形にしたい

Storage Manager用のWrapperを作成

import 'dart:js_util';
import 'package:js/js.dart';

@JS('navigator.storage')
external StorageManager get storageManager;

@JS()
@anonymous
class StorageManager {
  // jsのメソッドを呼ぶ
  external dynamic estimate();
}

@JS()
@anonymous
class StorageEstimate {
  external num get quota;
  external num get usage;

  external factory StorageEstimate({
    num quota,
    num usage,
  });

  factory StorageEstimate.fromJsObject(Object jsObject) {
    return StorageEstimate(
      quota: getProperty(jsObject, 'quota'),
      usage: getProperty(jsObject, 'usage'),
    );
  }
}

Future<StorageEstimate> fetchStorageEstimate() async {
  final jsEstimate = await promiseToFuture(storageManager.estimate());

  return StorageEstimate.fromJsObject(jsEstimate);
}

StorageEstimateクラスをfreezedを使用してimmutableにする

import 'dart:js_util';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:js/js.dart';

part 'storage_estimate.freezed.dart';


@JS('navigator.storage')
external StorageManager get storageManager;

@JS()
@anonymous
class StorageManager {
  external dynamic estimate();
}

@freezed
class StorageEstimate with _$StorageEstimate {
  const factory StorageEstimate({
    required num quota,
    required num usage,
  }) = _StorageEstimate;

  factory StorageEstimate.fromJsObject(Object jsObject) {
    return StorageEstimate(
      quota: getProperty(jsObject, 'quota') as num,
      usage: getProperty(jsObject, 'usage') as num,
    );
  }
}

Future<StorageEstimate> fetchStorageEstimate() async {
  // promiseToFutureメソッドでdartのFutureに変換する
  final jsEstimate = await promiseToFuture(storageManager.estimate());
  // Dartで定義した型にして返す
  return StorageEstimate.fromJsObject(jsEstimate);
}

使用

  final estimate = await fetchStorageEstimate();
  print('${estimate.quota}');
  print('${estimate.usage}');

参考

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?