如何将 Flutter 代码部署到 Web 端 | 开发者说·DTalk
2019-08-08 09:30
405 查看
原文链接:https://mp.weixin.qq.com/s?__biz=MzAwODY4OTk2Mg==\x26amp;mid=2652050011\x26amp;idx=1\x26amp;sn=19f1fb9b90fdaf26dcc3fa63e9415a10\x26amp;chksm=808cb21eb7fb3b0828b5c5fcfa268efdd2f3c8548a740e75f478e072f1e2502a92d0933a0dc8\x26amp;token=1519667995\x26amp;lang=z
本文原作者: IT工匠,原文发布于 IT工匠 (https://mp.weixin.qq.com/s/sTO43-F70b0yqTOfTbfW1Q)众所周知[code]Google对于
Flutter的期望是全平台统一
UI开发,号称要做一套 "一份代码、全平台部署" 的
UI框架,这一点在移动端已经很成熟了,国内有很多成功的案例,典型的像阿里的闲鱼客户端,但是
Flutter所声称的桌面端和
Web端的相关案例还很少,之前我写过一篇文章介绍如何将
Flutter代码部署成为桌面端程序,那么本文就该介绍如何将
Flutter部署为
Web应用了。本文将会以一个实例来带大家一步一步探寻如何将
Flutter应用程序部署到
Web端,我们先来看一下最终的效果:[/code] image-20190621195055828可以看到,就是一个简单的登录界面,没有太复杂的逻辑,旨在帮助大家走通
Flutter部署到
Web端的流程,至于实际的应用场景大家可以根据自己的需要自行开发。
开发环境配置
Flutter 1.5及更高的版本才支持
Web端部署,这主要指的是将
Dart编译为
JavaScript,所以,必须要确保我们本地的
Flutter SDK的版本在
v1.5.4以上,建议直接使用命令
flutter upgrade更新到最新版即可。
安装 flutter_web 编译工具
要想将Flutter代码编译为
Web端可部署的应用程序,必须安装
flutter_web,这是一个Flutter
官方为我们开发并维护的编译工具,直接使用以下命令安装即可:flutter pub global activate webdev安装完成后,需要配置环境变量,直接将
$HOME/.pub-cache/bin加入到你的环境变量中即可,由于电脑不同的操作系统配置环境变量的方式不同,这里就不一一展开赘述了,以
Mac操作系统为例:
cdvim .bash_profile
然后添加一行:
export PATH="$PATH":"$HOME/Flutter/flutter/.pub-cache/bin""$PATH":"$HOME/Flutter/flutter/.pub-cache/bin"退出并保存,使用如下命令使其生效:
source .bash_profile至此,我们的开发环境就搭建好了,可以看出,只要我们本地的
Flutter环境配置的没有问题,配置
Flutter for web只是多装了一个
flutter_web编译工具而已,非常简单。
创建项目
区别于普通的Flutter项目,由于
Flutter对
Web的支持目前还没有完全完成,相当于是一个供大家尝鲜的作品,所以创建
Flutter for web项目和普通
Flutter项目不一样,这里建议大家使用
Idea,我这里也以
Idea为例进行说明:
创建 Dart 项目,而不是 Flutter 项目
直接在Idea中新建项目,如下图所示: image-20190621200652154注意三点:
选择
Dart
项目,而不是新建Flutter
项目正确设置自己
dart sdk
的位置选择
Generate sample content
中的Flutter Web app
选项
Web了,在
Idea中应该可以直接点击运行按钮进行运行,或者可以在
Idea的终端中输入:
wevdev serve进行运行,初次编译可能会下一些本项目所依赖的包,需要一分多钟,后面编译会快很多,编译完成后会弹出一个浏览器的窗口 (注意,这里建议使用
Chrome浏览器,其他浏览器笔者没有测试过,按照官方的说法,目前支持最好的应该是
Chrome浏览器) 如下图: image-20190621202310684
我们来看看项目结构:
image-20190621202725911可以看到,大体的项目结构和普通的Flutter项目差不多,只是多了一个
web文件夹,下面是一些和
web相关的文件和资源,后面我会具体讲其用处。
编写代码
创建好项目之后,我们就可以着手代码的编写了,这里不再详细叙述代码怎么写,和普通Flutter编写代码的规则是一模一样的,这里我在
lib文件夹下新建了一个
pages文件夹,然后新建了
login_page.dart文件,编写登录界面的代码,完成后代码如下:
import 'package:flutter_web/material.dart';class LoginPage extends StatefulWidget { @override State<StatefulWidget> createState() => new _LoginState();}class _LoginState extends State<LoginPage> { static final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(); final TextEditingController _phoneController = new TextEditingController(); final TextEditingController _passwordController = new TextEditingController(); bool _correctPhone = true; bool _correctPassword = true; bool showProgress = false; void _checkInput() { if (_phoneController.text.isNotEmpty) { _correctPhone = true; } else { _correctPhone = false; } if (_passwordController.text.isNotEmpty) { _correctPassword = true; } else { _correctPassword = false; } setState(() {}); } _handleSubmitted(int flag) async { /** * flag=0:管理员登录 * flag=1:用户登录 */ _checkInput(); if (!_correctPassword || !_correctPhone) { return; } } @override Widget build(BuildContext context) { return new Scaffold( key: _scaffoldKey, resizeToAvoidBottomPadding: false, body: new Stack(children: <Widget>[ new Container( decoration: new BoxDecoration( image: new DecorationImage( image: new AssetImage('images/bg.jpeg'), fit: BoxFit.cover)), ), new GestureDetector( onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); }, ), _buildLogInWidgets(), ])); } _buildLogInWidgets() { Color mainColor = Colors.black; return new Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, //垂直方向对其方式 crossAxisAlignment: CrossAxisAlignment.start, //水平方向对其方式 children: <Widget>[ Center( child: new Container( child: Center( child: new CircleAvatar( backgroundImage: AssetImage("images/iron_man_icon.png")), ), ), ), new Center( 8000 child: new Container( width: MediaQuery.of(context).size.width * 0.5, child: new Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new Container( padding: const EdgeInsets.only(top: 32.0), child: new TextField( style: TextStyle(color: Colors.black), cursorColor: mainColor, controller: _phoneController, keyboardType: TextInputType.text, decoration: new InputDecoration( hintText: '用户名', hintStyle: TextStyle(color: mainColor), errorText: _correctPhone ? null : '用户名不可为空!', errorStyle: TextStyle(color: Colors.teal), icon: new Icon(Icons.people, color: mainColor), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: mainColor)), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: mainColor)), errorBorder: UnderlineInputBorder( borderSide: BorderSide(color: mainColor)), ), onSubmitted: (value) { _checkInput(); }, ), ), new Container( padding: const EdgeInsets.only(top: 32.0), child: new TextField( style: TextStyle(color: Colors.black), cursorColor: mainColor, controller: _passwordController, obscureText: true, keyboardType: TextInputType.text, decoration: new InputDecoration( hintText: '密码', hintStyle: TextStyle(color: mainColor), errorText: _correctPassword ? null : '密码不可为空!', errorStyle: TextStyle(color: Colors.teal), icon: new Icon(Icons.lock_outline, color: mainColor), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: mainColor)), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: mainColor)), errorBorder: UnderlineInputBorder( borderSide: BorderSide(color: mainColor)), ), onSubmitted: (value) { _checkInput(); }, ), ) ]), ), ), new Center( child: new Column( children: <Widget>[ new Container( width: MediaQuery.of(context).size.width * 0.2, child: new Material( child: new FlatButton( child: new Container( child: new Center( child: new Text( "登录", textScaleFactor: 1.5, style: new TextStyle( color: Colors.white, fontFamily: "Roboto"), )), ), onPressed: () { _handleSubmitted(0); }, ), color: Colors.teal, borderRadius: BorderRadius.circular(10.0), elevation: 5.0, ), ), new Center( child: Container( margin: EdgeInsets.only(top: 20), child: new FlatButton( child: new Text("没有帐户? 注册", style: new TextStyle(color: Colors.teal)), ), )), ], )), ], ); }}'package:flutter_web/material.dart';可以看到,代码和普通
class LoginPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _LoginState();
}
class _LoginState extends State<LoginPage> {
static final GlobalKey<ScaffoldState> _scaffoldKey =
new GlobalKey<ScaffoldState>();
final TextEditingController _phoneController = new TextEditingController();
final TextEditingController _passwordController = new TextEditingController();
bool _correctPhone = true;
bool _correctPassword = true;
bool showProgress = false;
void _checkInput() {
if (_phoneController.text.isNotEmpty) {
_correctPhone = true;
} else {
_correctPhone = false;
}
if (_passwordController.text.isNotEmpty) {
_correctPassword = true;
} else {
_correctPassword = false;
}
setState(() {});
}
_handleSubmitted(int flag) async {
/**
* flag=0:管理员登录
* flag=1:用户登录
*/
_checkInput();
if (!_correctPassword || !_correctPhone) {
return;
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
resizeToAvoidBottomPadding: false,
body: new Stack(children: <Widget>[
new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage('images/bg.jpeg'),
fit: BoxFit.cover)),
),
new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
),
_buildLogInWidgets(),
]));
}
_buildLogInWidgets() {
Color mainColor = Colors.black;
return new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, //垂直方向对其方式
crossAxisAlignment: CrossAxisAlignment.start, //水平方向对其方式
children: <Widget>[
Center(
child: new Container(
child: Center(
child: new CircleAvatar(
backgroundImage: AssetImage("images/iron_man_icon.png")),
),
),
),
new Center(
child: new Container(
width: MediaQuery.of(context).size.width * 0.5,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
padding: const EdgeInsets.only(top: 32.0),
child: new TextField(
style: TextStyle(color: Colors.black),
cursorColor: mainColor,
controller: _phoneController,
keyboardType: TextInputType.text,
decoration: new InputDecoration(
hintText: '用户名',
hintStyle: TextStyle(color: mainColor),
errorText: _correctPhone ? null : '用户名不可为空!',
errorStyle: TextStyle(color: Colors.teal),
icon: new Icon(Icons.people, color: mainColor),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: mainColor)),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: mainColor)),
errorBorder: UnderlineInputBorder(
borderSide: BorderSide(color: mainColor)),
),
onSubmitted: (value) {
_checkInput();
},
),
),
new Container(
padding: const EdgeInsets.only(top: 32.0),
child: new TextField(
style: TextStyle(color: Colors.black),
cursorColor: mainColor,
controller: _passwordController,
obscureText: true,
keyboardType: TextInputType.text,
decoration: new InputDecoration(
hintText: '密码',
hintStyle: TextStyle(color: mainColor),
errorText: _correctPassword ? null : '密码不可为空!',
errorStyle: TextStyle(color: Colors.teal),
icon: new Icon(Icons.lock_outline, color: mainColor),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: mainColor)),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: mainColor)),
errorBorder: UnderlineInputBorder(
borderSide: BorderSide(color: mainColor)),
),
onSubmitted: (value) {
_checkInput();
},
),
)
]),
),
),
new Center(
child: new Column(
children: <Widget>[
new Container(
width: MediaQuery.of(context).size.width * 0.2,
child: new Material(
child: new FlatButton(
child: new Container(
child: new Center(
child: new Text(
"登录",
textScaleFactor: 1.5,
style: new TextStyle(
color: Colors.white, fontFamily: "Roboto"),
)),
),
onPressed: () {
_handleSubmitted(0);
},
),
color: Colors.teal,
borderRadius: BorderRadius.circular(10.0),
elevation: 5.0,
),
),
new Center(
child: Container(
margin: EdgeInsets.only(top: 20),
child: new FlatButton(
child: new Text("没有帐户? 注册",
style: new TextStyle(color: Colors.teal)),
),
)),
],
)),
],
);
}
}
Flutter代码是一样的,只是需要注意以下几点:
包的使用
细心的同学可能会发现,我们这里导入的包是:
import 'package:flutter_web/material.dart';'package:flutter_web/material.dart';而普通
Flutter项目导入的是:
import 'package:flutter/material.dart';'package:flutter/material.dart';原则就是原来的
package:flutter改为
package:flutter_web,原来的
dart:ui改为
package:flutter_web_ui/ui.dart,当然,这些你只需要知道就好了,实际生产的时候直接快捷键按下,编辑器会自动帮我们导入正确的包。
资源的使用
我们之前使用资源文件 (比如图片) 的方式是在根目录下新建一个资源文件夹,然后将资源文件放在资源文件夹下,然后在pubspec.yaml文件中进行文件路径的声明,然后就可以使用了,在
Flutter for web中,我们需要将原来的资源文件夹从之前的项目根目录迁移到
web文件夹下,就像这样: image-20190621203620933然后就可以正常使用了,这也是迄今为止我发现的
Flutter for web和普通
Flutter项目的不同之处了。编写完布局文件后我们将
main.dart稍作修改,引入我们的
LoginPage:
import 'package:flutt 8000 er_web/material.dart';import 'package:flutter_web_demo/pages/login_page.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page22'), ); }}class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( body: LoginPage()); }}'package:flutter_web/material.dart';然后我们就可以运行起来看效果了: 和开篇的效果图一样,不再赘述。
import 'package:flutter_web_demo/pages/login_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page22'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
body: LoginPage());
}
}
总结
本文我们通过一个简单的实例带大家走了一遍Flutter在
Web端部署的流程,可以看到,目前
Flutter在
Web上的部署已经没有任何压力了,只是由于生态还不完整,很多库和包还不能用,所以目前还无法投入商用软件中,希望 Flutter 可以发展的越来越完善。同时,结合笔者个人的开发经验,建议大家开发
Flutter项目时一定不要怕麻烦,多用像
mvp这类的项目结构,这样可以大大提高开发效率。关于
Flutter for web的更多资料,可以参考
Flutter官方的仓库:
https://github.com/flutter/flutter_web。
"开发者说·DTalk" 面向中国开发者们征集 Google
移动应用 (apps & games) 相关的产品/技术内容。欢迎大家前来分享您对移动应用的行业洞察或见解、移动开发过程中的心得或新发现、以及应用出海的实战经验总结和相关产品的使用反馈等。我们由衷地希望可以给这些出众的中国开发者们提供更好展现自己、充分发挥自己特长的平台。我们将通过大家的技术内容着重选出优秀案例进行谷歌开发技术专家 (GDE) 的推荐。
点击屏末 | [strong]阅读原文[/strong] | 了解更多 "开发者说·DTalk" 活动详情与参与方式
相关文章推荐
- spring boot项目中使用spring-boot-devtools模块进行代码热部署,避免重新启动web项目
- 开发ASP.NET 2.0 Web应用程序时如何将App_Code文件夹中的共享代码配置生成多个Dll
- 大公司里如何开发和部署前端代码?
- 如何查看前端部署的tracker代码
- Web开发者指南:如何建立并运作一个互联网初创项目
- WEB开发:如何用js来模拟服务器的ajax响应,不依赖服务器来编写前端代码
- 一个Web应用(比如网站)是如何部署在多个web服务器上的?同步软件有讲到
- 如何使用 Docker 部署一个基于 Play Framework 的 Scala Web 应用?
- intellij IDEA如何将Web项目导出为WAR包,直接部署到tomcat或者Jboss上
- Web开发者不容错过的20段CSS代码
- Web开发者不容错过的20段CSS代码
- Myeclipse部署Web Project时如何输出日志
- 从0开始搭建自己的个人网站教程(三)如何把代码部署到虚拟主机
- 如何在centOS6.7上安装jdk、mysql、tomcat,以及部署打包成war包的web项目
- spring boot项目中使用spring-boot-devtools模块进行代码热部署,避免重新启动web项目
- spring boot项目中使用spring-boot-devtools模块进行代码热部署,避免重新启动web项目
- 如何在 Microsoft Visual Studio 2005 中直接Debug Community Server 2.0 的代码 与 Visual Studio 2005 Web Application Projects
- Web开发者必备的10个救命的PHP代码片段
- Web开发者必备:21个超实用PHP代码