创建一个支持 web 的新项目
当前,你需要 master 或者 dev 渠道的的 Flutter SDK 来获取 Web 支持:这里我们假定你已经安装了 Flutter 命令行工具,运行下面的命令需要安装 master 渠道最新的 SDK 噢:
你可以通过以下步骤创建一个支持 web 的新项目。
初始化
运行以下命令,使用最新的 beta 频道的 Flutter SDK,并开启 web 支持:
Run the following commands to use the latest version of the Flutter SDK from the beta channel and enable web support:
$ flutter channel beta
$ flutter upgrade
$ flutter config --enable-web
备忘
这里的 flutter upgrade 命令会在个人 fork 情况下失效,验证 origin 是否指向 “flutter/flutter” 仓库,可以通过下面命令:
$ cd <inside local copy of the flutter/flutter repo>
$ git remote get-url origin
https://github.com/flutter/flutter.git
开启 Web 支持
使用如下命令来开启 Web 支持:
$ flutter config --enable-web
这个命令只需要运行一次即可,它会创建一个 ~/.flutter_settings 的配置文件:
{
"enable-web": true
}
一旦开启了 Web 支持,运行 flutter devices 命令会输出一个名为 Chrome 的设备信息。
Once web is enabled, the flutter devices command outputs a Chrome device that opens the Chrome browser with your app running, and a Web Server that provides the URL serving the app.
$ flutter devices
2 connected device:
Web Server • web-server • web-javascript • Flutter Tools
Chrome • chrome • web-javascript • Google Chrome 81.0.4044.129
在开启了 Web 支持后,需要重启 IDE。你现在可以在设备下拉列表中看到 Chrome (web)。
运行 flutter run 命令将使用 Chrome 浏览器的 development compiler 来启动应用程序。当前连接的 Web 设备是 chrome,要在这个设备运行的话,无需特别声明使用它(当没有其他设备的时候)。
对已有的应用添加 Web 支持
对一个已有的工程添加 Web 支持,需要在工程根目录下输入下面的命令:
flutter create .
备忘
这些配置部分的步骤和工作,你只需要运行一次 flutter config --enable-web 就好。你可以随时通过 flutter config 来查看你的配置内容。
创建和运行
创建一个支持 Web 的 Flutter 工程与在支持其他平台的过程没有区别,请查看文档 创建一个 Flutter 工程。
Creating a new project with web support is no different than creating a new Flutter project for other platforms.
当你配置好对 Web 的支持后,你可以通过 IDE 或者命令行创建和运行一个 Web 应用。
集成开发环境 (IDE) 配置
IDE
在你配置好支持 Web 应用的环境后,如果 IDE 已经在运行了,请重启一下它。
在 IDE 里创建一个新的应用,它将会自动创建应用的对应的 iOS、Android 和 Web 版本。(如果启用了 桌面版应用支持,它还会创建 macOS 应用的版本)。在设备下拉菜单中,选择 Chrome (web),然后点击运行,你的应用就会在 Chrome 中打开。
命令行
为了创建一个既支持移动端又支持 Web 的新应用,将 myapp 替换成自己工程的名字,运行下面的命令:
$ flutter create myapp
$ cd myapp
要在 Chrome 的 localhost 中部署你的应用,从软件包根目录输入以下内容:
flutter run -d chrome
备忘
如果没有其他连接的设备,那么 -d chrome 是可选的。
运行 flutter run 命令将使用 Chrome 浏览器的 development compiler 来启动应用程序。
Build
运行下面命令以生成发行构建:
flutter build web
Release 构建产物使用 dart2js(不是 dartdevc)生成了一个单独的 JavaScript main.dart.js 文件。你可以通过 release 模式 (flutter run --release) 或者 flutter build web 创建一个发行构建。输出文件在 build/web 目录下,包括需要一起提供的 assets 资源文件。
了解更多相关信息,请查阅文档:Build and release a web app。
Add web support to an existing app
向现有应用添加 Web 支持
为了向现有应用添加 Web 支持,请在项目根目录下,在终端运行以下命令:
$ flutter create .