Как работать с flutter в visual studio code
This page describes how to create a new Flutter app from templates, run it, and experience “hot reload” after you make changes to the app.
Select your development tool of choice for writing, building, and running Flutter apps.
Create the app
- Open the IDE and select New Flutter Project.
- Select Flutter, verify the Flutter SDK path with the SDK’s location. Then click Next.
- Enter a project name (for example, my_app ).
- Select Application as the project type. Then click Next.
- Click Finish.
- Wait for Android Studio to create the project.
Note: When creating a new Flutter app, some Flutter IDE plugins ask for a company domain name in reverse order, something like com.example . The company domain name and project name are used together as the package name for Android (the Bundle ID for iOS) when the app is released. If you think that the app might be released, it’s better to specify the package name now. The package name can’t be changed once the app is released, so make the name unique.
The above commands create a Flutter project directory called my_app that contains a simple demo app that uses Material Components.
Tip: The code for your app is in lib/main.dart . For a high-level description of what each code block does, see the comments at the top of that file.
Run the app
- Locate the main Android Studio toolbar:
- In the target selector, select an Android device for running the app. If none are listed as available, select Tools > AVD Manager and create one there. For details, see Managing AVDs.
- Click the run icon in the toolbar, or invoke the menu item Run > Run.
After the app build completes, you’ll see the starter app on your device.
Starter app
Try hot reload
Flutter offers a fast development cycle with Stateful Hot Reload, the ability to reload the code of a live running app without restarting or losing app state. Make a change to app source, tell your IDE or command-line tool that you want to hot reload, and see the change in your simulator, emulator, or device.
Change the string
Important: Do not stop your app. Let your app run.
You’ll see the updated string in the running app almost immediately.
Profile or release runs
Important: Do not test the performance of your app with debug and hot reload enabled.
So far you’ve been running your app in debug mode. Debug mode trades performance for useful developer features such as hot reload and step debugging. It’s not unexpected to see slow performance and janky animations in debug mode. Once you are ready to analyze performance or release your app, you’ll want to use Flutter’s “profile” or “release” build modes. For more details, see Flutter’s build modes.
Important: If you’re concerned about the package size of your app, see Measuring your app’s size.
Create the app
- Invoke View > Command Palette.
- Type “flutter”, and select the Flutter: New Project.
- Select Application.
- Create or select the parent directory for the new project folder.
- Enter a project name, such as my_app , and press Enter.
- Wait for project creation to complete and the main.dart file to appear.
The above commands create a Flutter project directory called my_app that contains a simple demo app that uses Material Components.
Note: When creating a new Flutter app, some Flutter IDE plugins ask for a company domain name in reverse order, something like com.example . The company domain name and project name are used together as the package name for Android (the Bundle ID for iOS) when the app is released. If you think that the app might be released, it’s better to specify the package name now. The package name can’t be changed once the app is released, so make the name unique.
Warning: If VS Code was running during your initial Flutter setup, you might need to restart it for VS Code’s Flutter plugin to detect the Flutter SDK.
Tip: The code for your app is in lib/main.dart . For a high-level description of what each code block does, see the comments at the top of that file.
Run the app
- Locate the VS Code status bar (the blue bar at the bottom of the window):
- Select a device from the Device Selector area. For details, see Quickly switching between Flutter devices.
If no device is available, and you want to use a device simulator, click No Devices and click Start iOS Simulator to launch a simulator.
Warning: You might not see Start iOS Simulator option when you click No Devices in VS Code. If you’re on Mac, then you might have to run following command in terminal to launch a simulator.
On Windows or Linux, it’s not possible to launch an iOS simulator.
To setup a real device, follow the device-specific instructions on the Install page for your OS.
After the app build completes, you’ll see the starter app on your device.
Starter app
Try hot reload
Flutter offers a fast development cycle with Stateful Hot Reload, the ability to reload the code of a live running app without restarting or losing app state. Make a change to app source, tell your IDE or command-line tool that you want to hot reload, and see the change in your simulator, emulator, or device.
Change the string
Important: Do not stop your app. Let your app run.
You’ll see the updated string in the running app almost immediately.
Profile or release runs
Important: Do not test the performance of your app with debug and hot reload enabled.
So far you’ve been running your app in debug mode. Debug mode trades performance for useful developer features such as hot reload and step debugging. It’s not unexpected to see slow performance and janky animations in debug mode. Once you are ready to analyze performance or release your app, you’ll want to use Flutter’s “profile” or “release” build modes. For more details, see Flutter’s build modes.
Important: If you’re concerned about the package size of your app, see Measuring your app’s size.
Create the app
Use the flutter create command to create a new project:
It is also possible to pass other arguments to flutter create , such as the project name (pubspec.yml), the organization name, or to specify the programming language used for the native platform:
The command creates a Flutter project directory called my_app that contains a simple demo app that uses Material Components.
Tip: The code for your app is in lib/main.dart . For a high-level description of what each code block does, see the comments at the top of that file.
Run the app
Check that an Android device is running. If none are shown, follow the device-specific instructions on the Install page for your OS.
Run the app with the following command:
After the app build completes, you’ll see the starter app on your device.
Starter app
Try hot reload
Flutter offers a fast development cycle with Stateful Hot Reload, the ability to reload the code of a live running app without restarting or losing app state. Make a change to app source, tell your IDE or command-line tool that you want to hot reload, and see the change in your simulator, emulator, or device.
Change the string
Important: Do not stop your app. Let your app run.
You’ll see the updated string in the running app almost immediately.
Profile or release runs
Important: Do not test the performance of your app with debug and hot reload enabled.
So far you’ve been running your app in debug mode. Debug mode trades performance for useful developer features such as hot reload and step debugging. It’s not unexpected to see slow performance and janky animations in debug mode. Once you are ready to analyze performance or release your app, you’ll want to use Flutter’s “profile” or “release” build modes. For more details, see Flutter’s build modes.
Important: If you’re concerned about the package size of your app, see Measuring your app’s size.
Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.
Follow the Set up an editor instructions to install the Dart and Flutter extensions (also called plugins).
Updating the extension
Updates to the extensions are shipped on a regular basis. By default, VS Code automatically updates extensions when updates are available.
To install updates manually:
- Click the Extensions button in the Side Bar.
- If the Flutter extension is shown with an available update, click the update button and then the reload button.
- Restart VS Code.
Creating projects
There are a couple ways to create a new project.
Creating a new project
To create a new Flutter project from the Flutter starter app template:
- Open the Command Palette ( Ctrl + Shift + P ( Cmd + Shift + P on macOS)).
- Select the Flutter: New Project command and press Enter .
- Select Application and press Enter .
- Select a Project location.
- Enter your desired Project name.
Opening a project from existing source code
To open an existing Flutter project:
- Click File > Open from the main IDE window.
- Browse to the directory holding your existing Flutter source code files.
- Click Open.
Editing code and viewing issues
The Flutter extension performs code analysis that enables the following:
- Syntax highlighting
- Code completions based on rich type analysis
- Navigating to type declarations (Go to Definition or F12 ), and finding type usages (Find All References or Shift + F12 )
- Viewing all current source code problems (View > Problems or Ctrl + Shift + M ( Cmd + Shift + M on macOS)) Any analysis issues are shown in the Problems pane:
Running and debugging
Note: You can debug your app in a couple of ways.
- Using DevTools, a suite of debugging and profiling tools that run in a browser. DevTools replaces the previous browser-based profiling tool, Observatory, and includes functionality previously only available to Android Studio and IntelliJ, such as the Flutter inspector.
- Using VS Code’s built-in debugging features, such as setting breakpoints.
The instructions below describe features available in VS Code. For information on using launching DevTools, see Running DevTools from VS Code in the DevTools docs.
Start debugging by clicking Run > Start Debugging from the main IDE window, or press F5 .
Selecting a target device
When a Flutter project is open in VS Code, you should see a set of Flutter specific entries in the status bar, including a Flutter SDK version and a device name (or the message No Devices):
Note:
- If you do not see a Flutter version number or device info, your project might not have been detected as a Flutter project. Ensure that the folder that contains your pubspec.yaml is inside a VS Code Workspace Folder.
- If the status bar reads No Devices, Flutter has not been able to discover any connected iOS or Android devices or simulators. You need to connect a device, or start a simulator or emulator, to proceed.
The Flutter extension automatically selects the last device connected. However, if you have multiple devices/simulators connected, click device in the status bar to see a pick-list at the top of the screen. Select the device you want to use for running or debugging.
Are you developing for macOS or iOS remotely using Visual Studio Code Remote? If so, you might need to manually unlock the keychain. For more information, see this question on StackExchange.
Run app without breakpoints
- Click Run > Start Without Debugging in the main IDE window, or press Ctrl + F5 . The status bar turns orange to show you are in a debug session.
Run app with breakpoints
Click Run > Start Debugging in the main IDE window, or press F5 .
- The left Debug Sidebar shows stack frames and variables.
- The bottom Debug Console pane shows detailed logging output.
- Debugging is based on a default launch configuration. To customize, click the cog at the top of the Debug Sidebar to create a launch.json file. You can then modify the values.
Run app in debug, profile, or release mode
Flutter offers many different build modes to run your app in. You can read more about them in Flutter’s build modes.
Open the launch.json file in VS Code.
If you do not have a launch.json file, go to the Run view in VS Code and click create a launch.json file.
-
For example, if you want to run in debug mode, your launch.json might look like this:
Fast edit and refresh development cycle
Flutter offers a best-in-class developer cycle enabling you to see the effect of your changes almost instantly with the Stateful Hot Reload feature. See Using hot reload for details.
Advanced debugging
You might find the following advanced debugging tips useful:
Debugging visual layout issues
During a debug session, several additional debugging commands are added to the Command Palette and to the Flutter inspector. When space is limited, the icon is used as the visual version of the label.
Toggle Baseline Painting Causes each RenderBox to paint a line at each of its baselines. Toggle Repaint Rainbow Shows rotating colors on layers when repainting. Toggle Slow Animations Slows down animations to enable visual inspection. Toggle Debug Mode Banner Hides the debug mode banner even when running a debug build.
Debugging external libraries
By default, debugging an external library is disabled in the Flutter extension. To enable:
- Select Settings > Extensions > Dart Configuration.
- Check the Debug External Libraries option.
Editing tips for Flutter code
If you have additional tips we should share, let us know!
Assists & quick fixes
Quick fixes are similar, only they are shown with a piece of code has an error and they can assist in correcting it.
Wrap with new widget assist This can be used when you have a widget that you want to wrap in a surrounding widget, for example if you want to wrap a widget in a Row or Column . Wrap widget list with new widget assist Similar to the assist above, but for wrapping an existing list of widgets rather than an individual widget. Convert child to children assist Changes a child argument to a children argument, and wraps the argument value in a list. Convert StatelessWidget to StatefulWidget assist Changes the implementation of a StatelessWidget to that of a StatefulWidget , by creating the State class and moving the code there.
Snippets
Snippets can be used to speed up entering typical code structures. They are invoked by typing their prefix, and then selecting from the code completion window:
The Flutter extension includes the following snippets:
- Prefix stless : Create a new subclass of StatelessWidget .
- Prefix stful : Create a new subclass of StatefulWidget and its associated State subclass.
- Prefix stanim : Create a new subclass of StatefulWidget , and its associated State subclass including a field initialized with an AnimationController .
You can also define custom snippets by executing Configure User Snippets from the Command Palette.
Keyboard shortcuts
Hot reload During a debug session, clicking the Hot Reload button on the Debug Toolbar, or pressing Ctrl + F5 ( Cmd + F5 on macOS) performs a hot reload.
Keyboard mappings can be changed by executing the Open Keyboard Shortcuts command from the Command Palette.
Hot reload vs. hot restart
Hot reload works by injecting updated source code files into the running Dart VM (Virtual Machine). This includes not only adding new classes, but also adding methods and fields to existing classes, and changing existing functions. A few types of code changes cannot be hot reloaded though:
- Global variable initializers
- Static field initializers
- The main() method of the app
For these changes, fully restart your application without having to end your debugging session. To perform a hot restart, run the Flutter: Hot Restart command from the Command Palette, or press Ctrl + Shift + F5 ( Cmd + Shift + F5 on macOS).
Troubleshooting
Known issues and feedback
All known bugs are tracked in the issue tracker: Dart and Flutter extensions GitHub issue tracker.
We welcome feedback, both on bugs/issues and feature requests. Prior to filing new issues:
- Do a quick search in the issue trackers to see if the issue is already tracked.
- Make sure you are up to date with the most recent version of the plugin.
When filing new issues, include flutter doctor output.
Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.
To use the DevTools from VS Code, you need the Dart extension. If you’re debugging Flutter applications, you should also install the Flutter extension.
Start an application to debug
Start a debug session for your application by opening the root folder of your project (the one containing pubspec.yaml ) in VS Code and clicking Run > Start Debugging ( F5 ).
Launch DevTools
Once the debug session is active and the application has started, the Dart: Open DevTools command becomes available in the VS Code command palette:
The first time you run this (and subsequently when the DevTools package is updated), you are prompted to activate or upgrade DevTools.
Clicking the Open button uses pub global activate to activate the DevTools package for you. Next, DevTools launches in your browser and automatically connects to your debug session.
While DevTools is active, you’ll see them in the status bar of VS Code. If you’ve closed the browser tab, you can click the status bar to re-launch your browser, so long as there’s still a suitable Dart/Flutter debugging session available.
Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.
Одним из популярнейших текстовых редакторов на сегодняшний день является Visual Studio Code. И Google предоставляет для него плагин для разработки под Flutter.
Для его установки перейдем к пункту меню View -> Extensions .
После этого откроется панель расширений. Введем в поле поиска слово "Flutter":
Нужный плагин носит имя "Flutter" (как правило, первый результат среди результатов поиска). И для его установки нажмем на кнопку Install.
Поскольку этот плагин зависит от плагина для Dart, то плагин Dart также автоматически будет установлен.
После установки плагина создадим первый проект. Для этого перейдем к пункту меню View -> Command Palette . В открышееся окно поиска введем слово "flutter" и среди результатов выберем Flutter: New Application Project .
Затем в новом окне выберем папку, где будет располагаться проект
Затем в новом окне введем название проекта, например, "hello_app" и введем Enter
В итоге будет создан проект с той же структурой, что и в предыдущих статьях. А в текстовом редакторе будет открыт файл main.dart :
Для запуска приложения подключим мобильное устройство с Android к компьютеру, а в Visual Studio Code перейдем к пункту меню Run -> Start Debugging . (Если отладка нам неважна и мы хотим посто запустить проект, то выбирается пункт Run Without Debugging )
В результате будет построено приложение. Сверху VS Code ообразится панель для управления отладкой, а снизу ообразится вся отладочная информация
Начиная с версии 2.20 фреймворк Flutter поддерживает создание приложений под ОС Windows. Однако кроме самого фреймворка для создания приложений под Windows необходимо сделать еще ряд шагов:
Через установщик Visual Studio установить рабочую нагрузку "Разработка классических приложений на C++" (Desktop development with C++)
После этого в консоли/терминале необходимо выполнить следующую команду:
Для выполнения этой команды может потребоваться установить через Android SDK утилиту Android SDK Command-line tools
И если все установлено и настроено правильно, то при создании проекта в Android Studio в поле Platforms будет доступен пункт Windows :
Отметим этот пункт и создадим новый проект. И после создания проекта в его структуре будет создан каталог windows для файлов, которые предназначены для Windows:
Для запуска проекта на Windows в поле платформ запуска выберем пункт Windows (desktop) и запустим проект.
При запуске мы можем столкнуться с проблемой, что в определенном каталоге не найден файл app.so
Данная проблема связана с установленной версией Visual Studio. И в этом случае в качестве решения можно скопировать файл app.so из каталога ..\build\windows в каталог ..\build\windows\runner\Debug\data
И если после этого мы повторно запустим проект, то на экране отобразится окно приложения:
В качестве альтернативы можно запускать проект в режиме Profile Mode или Release Mode.
Читайте также: