Flutter приложение под windows

Начало работы с Flutter Desktop

С момента выпуска Flutter в декабре 2018 года он набрал обороты и быстро становится популярным выбором для многих профессиональных разработчиков мобильных устройств по всему миру.

Опираясь на успех языка Dart и экосистемы Flutter, поддержка настольных компьютеров предоставляет новые возможности для создания великолепных настольных приложений с чистыми и читаемыми кодовыми базами и высокопроизводительными двоичными файлами.

В этой статье мы рассмотрим процесс создания простого desktop приложения с помощью Flutter и рассмотрим возможности и проблемы использования этих инструментов для создания законченных приложений.

Требования

Для создания desktop приложений с помощью Flutter требуется современная среда Flutter SDK с включенной поддержкой рабочего стола:

  1. Если у вас его еще нет, загрузите Flutter для вашей ОС с их сайта.
  2. Переключитесь на главный канал с помощью $ flutter channel master
  3. Вы можете обновить Flutter (при необходимости) с помощью $ flutter upgrade

Чтобы включить поддержку для вашей целевой среды:

  1. Linux: $ flutter config —enable-linux-desktop
  2. MacOS: $ flutter config —enable-macos-desktop
  3. Window: $ flutter config —enable-windows-desktop

Команда flutter create в настоящее время поддерживает все еще не основные операционной системы (по состоянию на декабрь 2019 года) только MacOS. Для получения дополнительной информации о текущем и будущем статусе поддержки настольных компьютеров, можете посетить GitHub.

Настройка проекта

Чтобы создать приложение для macOS, просто запустите, $flutter create и проект будет создан. Для создания приложения, которое также может поддерживать Linux и Windows, проект Flutter предоставляет стартовый проект, поддерживающий все три среды, с проектом flutter-desktop-embedding.

Он может быть склонирован или загружен для использования в качестве отправной точки для новых проектов.

Пример проекта, использованный в этой статье, был создан путем клонирования рабочего стола флаттера с встраиванием репозитория и копированием содержимого example/ в новый проект. Для получения копии примера кода проекта этой статьи, проверьте этот репозиторий.

Давайте посмотрим на файл определения проекта, pubspec.yaml:

Для этого и других встроенных проектов для настольных компьютеров требуется последняя версия Flutter. В дополнение к нескольким типовым шрифтам была включена зависимость для простого Desktop плагина — нативная палитра цветов. Далее мы проверим код Dart для этого простого одноэкранного демонстрационного приложения.

Точка входа в приложение

Основной файл для этого приложения — стандартный lib/main.dart :

Функция main() запускает приложение и устанавливает целевую платформу отладки по умолчанию на fuchsia, которая представляет собой ОС, разрабатываемую в Google и включающую пользовательский интерфейс, созданный с помощью Dart и Flutter. Класс MyApp — это базовая реализация StatelessWidget, которая возвращает основной контейнер для самого приложения, со стандартом заголовка, темы и домашнего виджета для любого приложения Flutter.

Обратите внимание, что свойство darkTheme и его значение ThemeData.dark() обеспечивают темную тему, когда она запрашивается операционной системой, как в случае macOS с включенной темной темой для всей системы. Далее мы рассмотрим содержание страницы примера и ее назначение.

Домашний экран

Большая часть содержимого приложения для этой простой демонстрации находится в lib/home.dart :

В Home мы импортируем несколько пакетов (включая плагин color_panel ) и реализуем StatefulWidget, чтобы этот экран был в состоянии хранить и обновлять приложения. Dart и Flutter предоставляют отличные возможности для управления состоянием с использованием различных инструментов и шаблонов, самым простым из которых является виджет с состоянием, подобный показанному в этом файле.

Свойства, управляемые в состоянии этого виджета, включают цвет и счетчик. Методы _increment и _decrement используют метод setState для увеличения или уменьшения счетчика. Метод _showPanel запрашивает экземпляр ColorPanel из импортируемого плагина, а затем вызывает на нем show , который будет запрашивать нативный выбор цвета из операционной системы. Когда выбран цвет, setState используется для обновления состояния виджета новым цветом, который ставит его в очередь для перерисовки движком Flutter.

Windows install

System requirements

To install and run Flutter, your development environment must meet these minimum requirements:

  • Operating Systems: Windows 7 SP1 or later (64-bit), x86-64 based
  • Disk Space: 1.64 GB (does not include disk space for IDE/tools).
  • Tools: Flutter depends on these tools being available in your environment.
    • Windows PowerShell 5.0 or newer (this is pre-installed with Windows 10)

    Git for Windows 2.x, with the Use Git from the Windows Command Prompt option.

    If Git for Windows is already installed, make sure you can run git commands from the command prompt or PowerShell.

    Get the Flutter SDK

    Download the following installation bundle to get the latest stable release of the Flutter SDK:

    For other release channels, and older builds, see the SDK releases page.

    Extract the zip file and place the contained flutter in the desired installation location for the Flutter SDK (for example, C:\src\flutter ).

    Warning: Do not install Flutter in a directory like C:\Program Files\ that requires elevated privileges.

    If you don’t want to install a fixed version of the installation bundle, you can skip steps 1 and 2. Instead, get the source code from the Flutter repo on GitHub, and change branches or tags as needed. For example:

    You are now ready to run Flutter commands in the Flutter Console.

    Update your path

    If you wish to run Flutter commands in the regular Windows console, take these steps to add Flutter to the PATH environment variable:

    • From the Start search bar, enter ‘env’ and select Edit environment variables for your account.
    • Under User variables check if there is an entry called Path:
      • If the entry exists, append the full path to flutter\bin using ; as a separator from existing values.
      • If the entry doesn’t exist, create a new user variable named Path with the full path to flutter\bin as its value.

    You have to close and reopen any existing console windows for these changes to take effect.

    Note: As of Flutter’s 1.19.0 dev release, the Flutter SDK contains the dart command alongside the flutter command so that you can more easily run Dart command-line programs. Downloading the Flutter SDK also downloads the compatible version of Dart, but if you’ve downloaded the Dart SDK separately, make sure that the Flutter version of dart is first in your path, as the two versions might not be compatible. The following command tells you whether the flutter and dart commands originate from the same bin directory and are therefore compatible.

    As shown above, the command dart from the Flutter SDK doesn’t come first. Update your path to use commands from C:\path-to-flutter-sdk\bin\ before commands from C:\path-to-dart-sdk\bin\ (in this case). After restarting your shell for the change to take effect, running the where command again should show that the flutter and dart commands from the same directory now come first.

    However, if you are using PowerShell , in it where is an alias of Where-Object command, so you need to use where.exe instead.

    To learn more about the dart command, run dart -h from the command line, or see the dart tool page.

    Run flutter doctor

    From a console window that has the Flutter directory in the path (see above), run the following command to see if there are any platform dependencies you need to complete the setup:

    This command checks your environment and displays a report of the status of your Flutter installation. Check the output carefully for other software you might need to install or further tasks to perform (shown in bold text).

    The following sections describe how to perform these tasks and finish the setup process. Once you have installed any missing dependencies, you can run the flutter doctor command again to verify that you’ve set everything up correctly.

    Note: If flutter doctor returns that either the Flutter plugin or Dart plugin of Android Studio are not installed, move on to Set up an editor to resolve this issue.

    Warning: The flutter tool uses Google Analytics to anonymously report feature usage statistics and basic crash reports. This data is used to help improve Flutter tools over time.

    Flutter tool analytics are not sent on the very first run. To disable reporting, type flutter config —no-analytics . To display the current setting, type flutter config . If you opt out of analytics, an opt-out event is sent, and then no further information is sent by the Flutter tool.

    By downloading the Flutter SDK, you agree to the Google Terms of Service. Note: The Google Privacy Policy describes how data is handled in this service.

    Moreover, Flutter includes the Dart SDK, which may send usage metrics and crash reports to Google.

    Android setup

    Note: Flutter relies on a full installation of Android Studio to supply its Android platform dependencies. However, you can write your Flutter apps in a number of editors; a later step discusses that.

    Install Android Studio

    1. Download and install Android Studio.
    2. Start Android Studio, and go through the ‘Android Studio Setup Wizard’. This installs the latest Android SDK, Android SDK Command-line Tools, and Android SDK Build-Tools, which are required by Flutter when developing for Android.

    Set up your Android device

    To prepare to run and test your Flutter app on an Android device, you need an Android device running Android 4.1 (API level 16) or higher.

    1. Enable Developer options and USB debugging on your device. Detailed instructions are available in the Android documentation.
    2. Windows-only: Install the Google USB Driver.
    3. Using a USB cable, plug your phone into your computer. If prompted on your device, authorize your computer to access your device.
    4. In the terminal, run the flutter devices command to verify that Flutter recognizes your connected Android device. By default, Flutter uses the version of the Android SDK where your adb tool is based. If you want Flutter to use a different installation of the Android SDK, you must set the ANDROID_SDK_ROOT environment variable to that installation directory.

    Set up the Android emulator

    To prepare to run and test your Flutter app on the Android emulator, follow these steps:

    1. Enable VM acceleration on your machine.
    2. Launch Android Studio, click the AVD Manager icon, and select Create Virtual Device…
      • In older versions of Android Studio, you should instead launch Android Studio > Tools > Android > AVD Manager and select Create Virtual Device…. (The Android submenu is only present when inside an Android project.)
      • If you do not have a project open, you can choose Configure > AVD Manager and select Create Virtual Device…
    3. Choose a device definition and select Next.
    4. Select one or more system images for the Android versions you want to emulate, and select Next. An x86 or x86_64 image is recommended.
    5. Under Emulated Performance, select Hardware — GLES 2.0 to enable hardware acceleration.

    Verify the AVD configuration is correct, and select Finish.

    For details on the above steps, see Managing AVDs.

  • In Android Virtual Device Manager, click Run in the toolbar. The emulator starts up and displays the default canvas for your selected OS version and device.
  • Web setup

    Flutter has support for building web applications in the stable channel. Any app created in Flutter 2 automatically builds for the web. To add web support to an existing app, follow the instructions on Building a web application with Flutter when you’ve completed the setup above.

    Установка Flutter на Windows

    Для установки и запуска Flutter ваша среда разработки должна соответствовать этим минимальным требованиям:

    • Операционные системы: Windows 7 SP1 или более поздняя версия (64-разрядная)
    • Дисковое пространство: 1,32 ГБ (не включает дисковое пространство для IDE/инструментов).
    • Инструменты: Flutter зависит от того, доступны ли эти инструменты в вашей среде.
      • Windows PowerShell 5.0 или более новая (она предустановлена в Windows 10).
      • Git для Windows 2.x, с опцией Use Git из командной строки Windows Command Prompt. Если Git для Windows уже установлен, убедитесь, что вы можете запускать команды git’а из командной строки или PowerShell.

    Получение Flutter SDK

    1. Загрузите следующий установочный пакет, чтобы получить последний стабильный выпуск Flutter SDK:

    О других выпусках и старых сборках см. страницу архива SDK.

    2. Распакуйте zip-файл и поместите содержащийся в нем flutter в желаемое место установки SDK Flutter (например, C:\src\flutter ).

    Если вы не хотите устанавливать фиксированную версию установочного пакета, вы можете пропустить шаги 1 и 2. Вместо этого возьмите исходный код из Flutter repo на GitHub и измените ветки или теги по мере необходимости. Например:

    Теперь вы готовы запускать команды Flutter в консоли Flutter Console.

    Обновите свой PATH

    Если вы хотите запустить команды Flutter в обычной консоли Windows, выполните эти шаги, чтобы добавить Flutter в переменную окружения PATH:

    • В строке поиска Start введите ‘env’ (окр) и выберите Edit environment variables for your account (Редактировать переменные окружения).
    • В разделе User variables (Пользовательские переменные) проверьте, есть ли запись под названием Path (Путь):
      • Если запись существует, добавьте полный путь по адресу flutter\bin, используя ; в качестве разделителя от существующих значений.
      • Если запись не существует, создайте новую пользовательскую переменную с именем Path и полным путем к flutter\bin в качестве ее значения.

    Чтобы эти изменения вступили в силу, необходимо закрыть и снова открыть все существующие окна консоли.

    Запуск flutter doctor

    В консольном окне, в пути к которому находится каталог Flutter (см. выше), запустите следующую команду, чтобы узнать, есть ли какие-нибудь зависимости от платформы, необходимые для завершения установки:

    Эта команда проверяет ваше окружение и отображает отчет о состоянии установки Flutter. Внимательно проверьте вывод на наличие другого программного обеспечения, которое может понадобиться для установки или выполнения дальнейших задач (показан жирным шрифтом).

    В следующих разделах описано, как выполнить эти задачи и завершить процесс установки. После того, как вы установили все недостающие зависимости, вы можете запустить команду flutter doctor еще раз, чтобы убедиться, что вы все настроили правильно.

    Установка Android Studio

    • Скачайте и установите Android Studio.
    • Запустите Android Studio и пройдите через ‘Мастер установки Android Studio’. Это позволит установить новейший Android SDK, Android SDK Command Line Tools и Android SDK Build-Tools, которые необходимы Flutter при разработке для Android.

    Настройка вашего Android устройства

    Чтобы подготовиться к запуску и тестированию приложения Flutter на устройстве под управлением ОС Android, необходимо устройство под управлением ОС Android 4.1 (уровень API 16) или выше.

    • Включите опции «Разработчик» и отладку USB на вашем устройстве. Подробные инструкции доступны в документации по Android.
    • Только для Windows: установите драйвер Google USB.
    • С помощью USB-кабеля подключите телефон к компьютеру. Если на устройстве появится запрос, авторизуйте компьютер для доступа к устройству.
    • В терминале выполните команду «flutter devices», чтобы убедиться, что flutter распознает подключенное устройство Android. По умолчанию, Flutter использует версию Android SDK, основанную на adb tools. Если вы хотите, чтобы Flutter использовал другую установку Android SDK, вы должны установить переменную окружения ANDROID_SDK_ROOT в этот установочный каталог.

    Настройка Android эмулятора

    Чтобы подготовиться к запуску и тестированию вашего Flutter приложения на эмуляторе Android, выполните следующие действия:

    1. Включите VM-ускорение на вашей машине.
    2. Запустите Android Studio, щелкните значок AVD Manager и выберите Create Virtual Device…
      • В старых версиях Android Studio вместо этого необходимо запустить Android Studio > Tools > Android > AVD Manager и выбрать Create Virtual Device….. (Подменю Android присутствует только внутри проекта Android).
      • Если у вас нет открытого проекта, вы можете выбрать Configure > AVD Manager и выбрать Create Virtual Device….
    3. Выберите определение устройства и нажмите Next.
    4. Выберите один или несколько системных образов для версий Android, которые вы хотите эмулировать, и выберите Next. Рекомендуется образ x86 или x86_64.
    5. В разделе Emulated Performance выберите Hardware — GLES 2.0, чтобы включить аппаратное ускорение.
    6. Убедитесь в правильности настройки AVD и выберите Finish (Завершить).

    Для получения более подробной информации о вышеописанных шагах смотрите раздел Управление AVD.

    7. В менеджере виртуальных устройств Android нажмите кнопку Run на панели инструментов. Эмулятор запустится и отобразит экран по умолчанию для выбранной версии ОС и устройства.

    Flutter имеет раннюю поддержку создания веб-приложений с использованием бета-версии Flutter. Чтобы добавить поддержку веб-разработки, следуйте этим инструкциям после завершения установки, описанной выше.

    Читайте также:  Wcp watermark editor для windows 10
Оцените статью