LoginSignup
1
1

Flutter on Desktopでウィンドウをリサイズ

Last updated at Posted at 2024-02-10

image.png

やりたいこと

Flutter on Desktopでウィンドウサイズを指定したい

環境環境

Flutter 3.16.0 • channel stable • https://github.com/flutter/flutter.git
Tools • Dart 3.2.0 • DevTools 2.28.2
Windows 10 Pro 22H2 開発者モード
VS Code 1.86.1

この記事を参考にしていただく条件

Flutter on Desktopの開発環境を構築済み

C++で対応(WindowsOS限定)

main.cppをのぞいてみる

Youre Flutte App
/windows
/runner
/main.cpp

main.cpp
 Win32Window::Point origin(10, 10);
 Win32Window::Size size(1280, 720);
 if (!window.Create(L"flutter_sticky", origin, size)) {
   return EXIT_FAILURE;
 }

ウィンドウサイズを指定しているメソッドがありますね。ここを書き換えたらサイズ指定できました。

win32_windows.cppを確認する

Youtre Flutte App
/windows
/runner
/win32_windows.cpp

win32_windows.cpp
  HWND window = CreateWindow(
      window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
      Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
      Scale(size.width, scale_factor), Scale(size.height, scale_factor),
      nullptr, nullptr, GetModuleHandle(nullptr), this);

bool Win32Window::Createメソッドの中にネストされたCreateWindowクラスがあり、そこで定義されていることがわかります。

プラグインで対応(ただしメンテされてないっぽい)

GoogleのGitのリポジトリにプロジェクトがありました。メンテが止まっているような雰囲気ですが、とりあえずやってみます。

/pluginに移動するとプラグインの設定例があります。

pubspec.yaml
dependencies:
  ...
  menubar:
    git:
      url: https://github.com/google/flutter-desktop-embedding.git
      path: plugins/menubar
      ref: INSERT_HASH_HERE

この例がわかりづらかったのですがこれはmenubarを使いたい場合の例という意味のようです。今回使いたいのはwindws_reseizeなのでコピペして次のように書き換えます。

pubspec.yaml
window_size:
    git:
      url: https://github.com/google/flutter-desktop-embedding
      path: plugins/window_size
      ref: a738913

INSERT_HASH_HEREにはコミットのハッシュ値を貼り付けます。わ、2年前のコミットだ。

main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:window_size/window_size.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  if (Platform.isWindows) {
    setWindowTitle('ぼくのFlutter Windows App');
    setWindowFrame(const Rect.fromLTWH(100, 100, 500, 500));
    setWindowMinSize(const Size(500, 500));
    //setWindowMaxSize(Size.infinite);
    setWindowMaxSize(const Size(500, 500));
    setWindowVisibility(visible: false);
  }

  runApp(const MyApp());
}

あとは野となれ山となれ。setWindowVisibilityでウィンドウが消えるかと思ったんだけど消えませんでした。

次にやりやいこと

ウィンドウを閉じるときのイベントを取得

Flutter on Desktopでウィンドウを閉じるときのイベントを取得したいときはこのパッケージが良さそうです。まだReadmeを眺めただけですがイベントリスナーは一通り揃っているので自前で実装する必要がなくて助かります。それにしてもクロスプラットフォームだけあってLinuxも実装しているのが素晴らしい。早くDebianのGnomeで試してみたいです。

ウィンドウの位置を記憶して次回起動時に反映する

fromLTWHの第一引数・第二引数をjsonで読み書きすれば出来そう。

ごあいさつ

今回が初投稿になります。ぼく自身みなさんの記事が理解できないことも多いので、自分では当たり前のことでもなるべく細かく書くように心がけていこうと思います。

この記事の続き

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