- How to install Flutter on Mac & Windows
- Learn about Flutter and how to set it up on Windows and Mac systems
- What is Flutter?
- What does Flutter do?
- What technology is Flutter built with?
- Why use Flutter?
- How to Install Flutter on Windows?
- Minimum System Requirements
- Get the Flutter SDK
- Flutter SDK releases
- Select from the following scrollable list: Select from the following scrollable list: Select from the following…
- Update your path
- Run flutter doctor
- Android Setup
- Install Android Studio
- Set up your Android device
- Install the Flutter and Dart plugins
- How to Install Flutter on MacOS?
- Minimum System Requirements
- Get the Flutter SDK
- Flutter SDK releases
- Select from the following scrollable list: Select from the following scrollable list: Select from the following…
- Run flutter doctor
- Fix license issue in Android studio
- Fix iOS toolchain issues
- Update iOS-deploy
- Android Studio — Install Flutter and Dart plugins
- Install VSCode Flutter Extension
- iOS Setup
- Install Xcode
- Set up the iOS simulator
- Create and run a simple Flutter app
- Deploy to iOS devices
- Android setup
- Install Android Studio
- Set up your Android device
- Set up the Android emulator
- Congratulations!
- Flutter I — Введение и установка
- Почему именно Flutter?
- Установка
- Первые шаги (Пишем Hello World!)
- Заключение
How to install Flutter on Mac & Windows
Learn about Flutter and how to set it up on Windows and Mac systems
In this post, we’ll have an overview of Flutter, the latest buzz in the App Development market. Flutter is gaining popularity faster than any other framework. Some say it is Google’s answer to Facebook’s React Native, but that debate is for later. Let’s learn the basics of Flutter and how to start using it.
What is Flutter?
Flutter is Google’s portable UI toolkit for crafting high-quality native experiences for mobile, web and desktop in record time. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source.
What does Flutter do?
For users, Flutter makes beautiful app UIs come to life.
For developers, Flutter lowers the bar to entry for building mobile apps. It speeds up the development of mobile apps and reduces the cost and complexity of app production across iOS and Android.
For designers, Flutter helps deliver the original design vision, without loss of fidelity or compromises. It also acts as a productive prototyping tool.
What technology is Flutter built with?
Flutter is built with C, C++, Dart, and Skia (a 2D rendering engine). See this architecture diagram for a better picture of the main components.
Why use Flutter?
- Develop for iOS and Android from a single codebase
- Do more with less code, even on a single OS, with a modern, expressive language and a declarative approach
- Experiment by changing code and reloading as your app runs (with hot reload)
- Fix crashes and continue debugging from where the app left off
- Benefit from a rich set of Material Design and Cupertino (iOS-flavor) widgets built using Flutter’s own framework
- Realize custom, beautiful, brand-driven designs, without the limitations of OEM widget sets
How to Install Flutter on Windows?
Minimum System Requirements
- Operating Systems: Windows 7 or later [64-bit]
- Disk Space: 400 MB
- Git for Windows
Get the Flutter SDK
- Download Latest Flutter SDK here:
Flutter SDK releases
Select from the following scrollable list: Select from the following scrollable list: Select from the following…
- Unzip the downloaded zip in C:\flutter .
- Locate flutter_console.bat inside the flutter directory and start it by double-clicking.
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, type ‘env’ and select Edit environment variables for your account
- Under User variables check if there is an entry called Path:
- If the entry does exist, append the full path to flutter\bin using ; as a separator from existing values.
- If the entry does not exist, create a new user variable named Path with the full path to flutter\bin as its value.
Note that you will have to close and reopen any existing console windows for these changes to take effect.
Run flutter doctor
From a console window which 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 may need to install or further tasks to perform (shown in bold text).
Android Setup
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.
Install Android Studio
- Download and install Android Studio.
- Start Android Studio, and go through the ‘ Android Studio Setup Wizard’. This installs the latest Android SDK, Android SDK Platform-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’ll need an Android device running Android 4.1 (API level 16) or higher.
- Enable Developer Options and USB debugging on your device. Detailed instructions are available in the Android documentation.
- Windows-only: Install the Google USB Driver
- Using a USB cable, plug your phone into your computer. If prompted on your device, authorize your computer to access your device.
- 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_HOME environment variable to that installation directory.
Install the Flutter and Dart plugins
- Start Android Studio.
- Open plugin preferences ( File > Settings > Plugins).
- Select Browse repositories, select the Flutter plugin and click Install.
- Click Yes when prompted to install the Dart plugin.
- Click Restart when prompted.
How to Install Flutter on MacOS?
Minimum System Requirements
- Operating Systems: macOS [64-bit]
- Disk Space: 700 MB
- Git for macOS
Get the Flutter SDK
- Download Latest Flutter SDK here:
Flutter SDK releases
Select from the following scrollable list: Select from the following scrollable list: Select from the following…
- Extract the file in the desired location e.g.
- Add the flutter tool to your path. To do this, open your bash profile from your terminal (might need sudo)
Add your flutter path to the $PATH variable in bash_profile.
E.g. If you extracted flutter in your Applications folder, your path will be /Applications/flutter/bin . Add this to the existing $PATH variable by using : in between two paths. Once added, save and close the bash_profile . Run terminal again and check the $PATH by running
You should see your Flutter path added to the $PATH
- Run flutter precache in the terminal.
Run flutter doctor
Run the following command to see if there are any dependencies you need to install to complete the setup (for verbose output, add the -v flag):
This command checks your environment and displays a report to the terminal window. The Dart SDK is bundled with Flutter; it is not necessary to install Dart separately. Check the output carefully for other software you may need to install or further tasks to perform (shown in bold text).
For example: If you haven’t used Flutter before, you might see an output like this by running flutter doctor
You can see there are several things to be done to begin using Flutter in this Mac. To correct these issues, let’s run following commands
Fix license issue in Android studio
Fix iOS toolchain issues
( Install Xcode command line tools if you are on Mac OS Mojave)
Update iOS-deploy
brew does not maintain it any longer, as flutter doctor suggests
Android Studio — Install Flutter and Dart plugins
- Start Android Studio.
- Open plugin preferences ( Preferences > Plugins on macOS, File > Settings > Plugins on Windows).
- Select Browse repositories, select the Flutter plugin and click Install.
- Click Yes when prompted to install the Dart plugin.
- Click Restart when prompted.
Install VSCode Flutter Extension
Now all issues should be gone
iOS Setup
Install Xcode
To develop Flutter apps for iOS, you need a Mac with Xcode 9.0 or newer:
- Install Xcode 9.0 or newer (via web download or the Mac App Store).
- Configure the Xcode command-line tools to use the newly-installed version of Xcode by running the following from the command line:
- This is the correct path for most cases, when you want to use the latest version of Xcode. If you need to use a different version, specify that path instead.
- Make sure the Xcode license agreement is signed by either opening Xcode once and confirming or running sudo xcodebuild -license from the command line.
With Xcode, you’ll be able to run Flutter apps on an iOS device or on the simulator.
Set up the iOS simulator
To prepare to run and test your Flutter app on the iOS simulator, follow these steps:
- On your Mac, find the Simulator via Spotlight or by using the following command:
- Make sure your simulator is using a 64-bit device (iPhone 5s or later) by checking the settings in the simulator’s Hardware > Device menu.
- Depending on your development machine’s screen size, simulated high-screen-density iOS devices may overflow your screen. Set the device scale under the Window > Scale menu in the simulator.
Create and run a simple Flutter app
To create your first Flutter app and test your setup, follow these steps:
- Create a new Flutter app by running the following from the command line:
A my_app directory is created, containing Flutter’s starter app.
CD into this directory:
To launch the app in the Simulator, ensure that the Simulator is running and enter:
Deploy to iOS devices
To deploy your Flutter app to a physical iOS device, you’ll need some additional tools and an Apple account. You’ll also need to set up physical device deployment in Xcode.
- Install homebrew.
- Ensure that homebrew is up to date:
- Install the tools for deploying Flutter apps to iOS devices by running the following commands:
Android setup
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 will discuss that.
Install Android Studio
- Download and install Android Studio.
- Start Android Studio, and go through the ‘ Android Studio Setup Wizard’. This installs the latest Android SDK, Android SDK Platform-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’ll need an Android device running Android 4.1 (API level 16) or higher.
- Enable Developer Options and USB debugging on your device. Detailed instructions are available in the Android documentation.
- Windows-only: Install the Google USB Driver
- Using a USB cable, plug your phone into your computer. If prompted on your device, authorize your computer to access your device.
- In the terminal, run the flutter devices command to verify that Flutter recognizes your connected Android device.
- Once ready, run flutter run again to run the app on 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_HOME 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:
- Enable VM acceleration on your machine.
- Launch Android Studio > Tools > Android > AVD Manager and select Create Virtual Device. (The Android submenu is only present when inside an Android project.)
- Choose a device definition and select Next.
- Select one or more system images for the Android versions you want to emulate, and select Next. An x86 or x86_64image is recommended.
- 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.
Congratulations!
YaY. 👻 You’re almost done. Now, you are ready to design beautiful Android and iOS Apps with Flutter.
Источник
Flutter I — Введение и установка
Flutter — новый инструмент от Google, позволяющий разработчикам писать кроссплатформенные приложения, которые можно запускать на различных системах (например, на Android или iOS) с общей кодовой базой.
Сам инструмент написан на C и C++. Предоставляет движок для 2D рендеринга, React-подобный FRP фреймворк и набор виджетов в стиле Material Design. На данный момент распространяется версия alpha:0.0.20, но несмотря на довольно «сырую» версию, уже можно создавать продвинутый интерфейс, работать с сетью и даже с файловой системой.
Подход Flutter отличается от инструментов, работающих через WebView и выполняющих HTML, CSS и Javascript (например Cordova), — он заключается в использовании Dart как единственного язык программирования. Dart довольно прост в изучении, а если вы ещё и знаете Java, то, считайте, 75% работы сделано, и на Dart можно перейти всего за пару дней.
Приложения компилируются в нативный код при сборке для релиза. Благодаря этому повышается производительность и уменьшается задержка при работе с интерфейсом. При сборке в режиме отладки (и выявлении возможных багов) Flutter также выполняет некоторые задачи, которые могут замедлять приложение. В таких случаях Flutter будет показывать надпись “Slow Mode” в правом верхнем углу экрана.
Почему именно Flutter?
Кроме того, что вы делаете приложение сразу под несколько систем (Android и iOS), код Flutter очень выразителен. То есть потребуется написать меньше кода чем если бы вы писали нативное приложение под одну платформу.
Производительность и отклик пользовательского интерфейса.
Ещё один плюс Flutter — он ориентирован на Material Design и предоставляет множество возможностей для работы с ним.
Google также использует Flutter для разработки пользовательского интерфейса своей новой системы Fuchsia.
Установка
Так как Flutter ещё в процессе разработки и постоянно обновляется, процесс установки со временем может поменяться. Актуальную инструкцию по установке можно найти на сайте Flutter.
Мы будем пользоваться версией 0.0.20+.alpha. (Прим.перев.: на данный момент установка возможна только под Mac и Linux (64-bit))
Шаг 1. Клонирование
Клонируйте ветку alpha из репозитория Flutter при помощи Git (SourceTree, Github Desktop…) и добавьте директорию bin в PATH.
Шаг 2. Проверка зависимостей
Запустите Flutter doctor, чтобы установить все необходимые зависимости.
Шаг 3. Установка платформ
Дальше мы установим платформы для разработки. Мы можем установить обе или ограничиться одной, для которой хотим написать приложение.
В случае с Android необходимо установить Android SDK. Можете просто установить Android Studio, SDK будет в комплекте. В случае, если Android Studio установлена не в директорию по умолчанию, необходимо добавить переменную ANDROID_HOME в PATH, указав новое расположение, куда был установлен SDK.
В случае с iOS необходим xCode версии 7.2 или выше. Для запуска приложений на физическом устройстве необходим дополнительный инструмент. Его можно установить при помощи Homebrew.
Шаг 4. Конфигурация Atom
Рекомендуется использовать текстовый редактор Atom с установленными плагинами Flutter и Dart.
Установка плагина Flutter для Atom:
- Запустите Atom.
- Packages > Settings View > Install Packages/Themes.
- Напишите в поле Install Packages слово ‘flutter’, затем нажмите кнопку Packages.
- Выберите Flutter и установите.
Откройте Packages > Flutter > Package Settings и выставьте в FLUTTER_ROOT путь, куда был склонирован Flutter SDK.
Затем Packages > Dart > Package Settings и выставьте переменную с расположением dart sdk, обычно это bin/cache/dart-sdk в директории Flutter.
Если у вас Mac, запустите Atom > Install Shell Commands чтобы установить shell-команды.
И напоследок запустите ещё раз Flutter doctor, чтобы удостовериться, что всё в порядке.
Вывод из консоли ниже показывает, что процесс установки успешен, но среда iOS ещё не отвечает всем необходимым требованиям.
Первые шаги (Пишем Hello World!)
Давайте создадим простенькое приложение и посмотрим Flutter в действии. В последующих статьях примеры будут куда сложнее и увлекательнее.
Запустите Packages → Flutter → create new Flutter Project. В директории lib есть файл main.dart, откройте его и сотрите весь код.
Выполнение кода Dart начинается с функции main, которая должна быть включена в файл main.dart.
Теперь импортируем библиотеку material, она предоставляет нам функцию для запуска приложений.
Эта функция называется runApp и принимает виджет (Widget) в качестве параметра. Виджет можно сравнить с представлением (View) в Android или iOS, чтобы иметь общее представление, но, само собой, между ними есть и отличия. То есть в Flutter весь интерфейс строится на использовании виджетов и весь код пишется на Dart. Например в Android надо было бы использовать XML для описания представлений.
Начнём с того, что выведем при помощи виджета Text произвольный текст.
Теперь запускаем приложение через Atom.
Как видно, текст появился за статус-баром. Так произошло потому, что туда установлены координаты Flutter (0,0).
Давайте добавим отступов, чтобы исправить это. Поскольку пользовательский интерфейс Flutter строится на виджетах, отступы тоже будут виджетом. Возможно, для людей с опытом разработки на Android и iOS (где отступы всего лишь свойства представления) это звучит дико. Нам же сейчас нужно добавить виджет Padding и указать виджет Text как дочерний элемент.
В примере выше создан виджет Padding, в котором отступы установлены на 24 при помощи объекта EdgeInsets, а в качестве дочернего элемента указан виджет Text. Запустите приложение и увидите, что текст теперь ниже.
Примечание: если вы знакомы с Java, то имейте в виду, const EdgeInsets.only(top: 24.0) всего лишь вызов конструктора EdgeInsets. Он возвращает экземпляр объекта, который будет константой времени компиляции. В этом разница между Java и Dart, больше информации о конструкторах в Dart можете найти здесь.
Воспользуемся виджетом Center, чтобы разместить текст в центре экрана.
Оба виджета, Padding и Center, предоставляют атрибут, называемый child, используемый для указания дочернего элемента. На самом деле это одна из особенностей, делающих Flutter таким мощным инструментом. Каждый виджет может иметь дочерние элементы, благодаря чему одни виджеты могут быть вложены в другие виджеты. Так, например, Text может быть вложен в Padding, который будет вложен в Center.
Заключение
В первой статье из цикла статей про Flutter мы рассмотрели, как можно при помощи всего нескольких строк кода вывести текст в приложении. В последующих статьях мы сосредоточимся на более сложных интерфейсах, чтобы показать, как их просто реализовать (по сравнению с нативным способом).
Источник