Flutter vs code add android device

Visual Studio Code

Installation and setup

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:

  1. Click the Extensions button in the Side Bar.
  2. If the Flutter extension is shown with an available update, click the update button and then the reload button.
  3. 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:

  1. Open the Command Palette ( Ctrl + Shift + P ( Cmd + Shift + P on macOS)).
  2. Select the Flutter: New Project command and press Enter .
  3. Select Application and press Enter .
  4. Select a Project location.
  5. Enter your desired Project name.

Opening a project from existing source code

To open an existing Flutter project:

  1. Click File > Open from the main IDE window.
  2. Browse to the directory holding your existing Flutter source code files.
  3. 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

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

    If desired, set breakpoints in your source code.

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.

In the configurations section, change the flutterMode property to the build mode you want to target.

    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:

  1. Select Settings > Extensions > Dart Configuration.
  2. 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

Assists are code changes related to a certain code identifier. A number of these are available when the cursor is placed on a Flutter widget identifier, as indicated by the yellow lightbulb icon. The assist can be invoked by clicking the lightbulb, or by using the keyboard shortcut Ctrl + . ( Cmd + . on Mac), as illustrated here:

Читайте также:  Как выслать геолокацию с андроида

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

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.

Источник

Как настроить устройства для VS-кода для эмулятора Flutter

Я хотел бы использовать VS Code в качестве редактора для разработки Flutter, но я не знаю, как запустить эмулятор. Я установил VS-код на Ubuntu 17.10.

я следовал первой половине инструкций, как указано на Flutter: Начало Работы страница (создать новое приложение). Затем я столкнулся с неприятностями во втором тайме:

запустить приложение

  1. убедитесь, что целевое устройство выбрано в правом нижнем углу угол VS кода
  2. Нажмите кнопку F5 на клавиатуре или вызовите Debug>начать отладку
  3. дождитесь запуска приложения
  4. если все работает, после того, как приложение было построено, вы должны увидеть свое стартовое приложение на своем устройстве или симуляторе:
Читайте также:  Смайлики айос для андроид

проблема в том, что в нижнем правом углу «нет устройств.»

Как подключить устройство? Я нигде не могу найти инструкций.

8 ответов

С version 2.13.0 Дарт код, эмуляторы могут быть запущены непосредственно из кода, но эта функция зависит от поддержки инструментов Flutter, что означает, что он будет показывать только эмуляторы при использовании совсем недавно Flutter SDK. Главный канал Flutter уже имеет это изменение, но может потребоваться немного больше времени для фильтрации через dev и бета-каналы.

я протестировал эту функцию и очень хорошо работал на flutter версии 0.5.6-pre.61 (мастер канал)

вы можете подключить телефон Android через USB-кабель, а затем он покажет устройство в нижней панели.(Обратите внимание, что ADB должен быть установлен. Нажмите здесь дополнительные)

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

для тех, кто использует Mac, вы можете перейти к терминалу и ввести

и эта команда откроет симулятор.

после этого просто перейдите к опции отладки и нажмите»Начать Отладку«

если вы хотите протестировать эмулятор Android:

то, что я сделал, это сначала пойти в Android Studio и открыть виртуальное устройство с AVD Manager. После этого вы см. другие устройства в коде Visual Studio

в правом нижнем углу вы увидите, что теперь у вас подключено 2 устройства. Теперь вы можете протестировать любое из этих устройств.

вам не нужна Android Studio для создания или запуска виртуального устройства. Просто используйте sdkmanager и avdmanager из инструментов Android sdk.

используйте sdkmanager для загрузки системного образа Android для системы x86.
например, sdkmanager «system-images; android-21; по умолчанию; x86_64»

затем создайте новое виртуальное устройство с помощью avdmanager.
например, avdmanager создать avd —имя AndroidDevice01 —пакет «system-images; android-21; по умолчанию; x86_64»

затем запустить новое виртуальное устройство с помощью эмулятора. Если у вас его нет, просто установите его с помощью sdkmanager.
например, эмулятор-avd AndroidDevice01

Если вы перезапустите VSCode и загрузите проект Flutter. Новое устройство должно появится в правом нижнем углу колонтитула.

в качестве альтернативы, если вы включаете режим разработчика и (ADB) по-прежнему необходим, вы можете использовать подключение к устройству.

чтобы включить режим разработчика, перейдите в настройки телефона > О телефоне > нажмите buildnumber 7 раз

Как только вы включили его и подключили устройство, вы можете начать видеть устройство в VSCode

VS код должен знать, где Android SDK установлен в вашей системе. В Windows установите переменную среды «ANDROID_SDK_ROOT» в корневую папку Android SDK.

Plus: всегда проверяйте вкладки» вывод «и» консоль отладки » на наличие ошибок и информации.

чтобы выбрать устройство, вы должны сначала запустить оба, android studio и виртуальное устройство. Затем visual studio code отобразит это виртуальное устройство в качестве опции.

во-первых, вы должны установить Android Sutdio и Xcode для создания эмулятора телефона.

в VSCode вы можете использовать эмулятор Android IOS плагин для установки пути эмулятора для запуска.

Источник

Оцените статью