手把手带你使用Flutter开发web应用程序(flutter web开发)

Flutter系列的文章我会持续更新,如果觉得这里代码排版不是很舒服的读者可以关注我的微信公众号“IT工匠”,我会同步更新,另外微信公众号上还有很多互联网必备资源(涉及算法、数据结构、java、深度学习、计算机网络、python、Android等互联网技术资料),欢迎大家关注、交流。

众所周知Google对于Flutter的期望是全平台统一UI开发,号称要做一套“一份代码、全平台部署”的UI框架,这一点在移动端已经很成熟了,国内有很多成功的案例,典型的像阿里的闲鱼客户端,但是Flutter所声称的桌面端和Web端的相关案例还很少,之前我写过一篇文章介绍如何将Flutter代码部署成为桌面端程序,那么本文就该介绍如何将Flutter部署为Web应用了。

本文将会以一个实例来带大家一步一步探寻如何将Flutter应用程序部署到web端,我们先来看一下最终的效果:

手把手带你使用Flutter开发web应用程序(flutter web开发)

可以看到,就是一个简单的登录界面,没有太复杂的逻辑,旨在帮助大家走通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\”

退出并保存,使用如下命令使其生效:

source .bash_profile

至此,我们的开发环境就搭建好了,可以看出,只要我们本地的Flutter环境配置的没有问题,配置Flutter for web只是多装了一个flutter_web编译工具而已,非常简单。

创建项目

区别于普通的Flutter项目,由于Flutter对web的支持目前还没有完全完成,相当于是一个供大家尝鲜的作品,所以创建Flutter for web项目和普通Flutter项目不一样,这里建议大家使用Idea,我这里也以idea为例进行说明:

创建Dart项目,而不是Flutter项目

直接在Idea中新建项目,如下图所示:

手把手带你使用Flutter开发web应用程序(flutter web开发)

注意三点:

  1. 选择Dart项目,而不是新建Flutter项目
  2. 正确设置自己dart sdk的位置
  3. 选择Generate sample content中的Flutter Web App选项

创建完成后我们的项目就默认支持部署到Web了,在Idea中应该可以直接点击运行按钮进行运行,或者可以在Idea的终端中输入:

wevdev serve

进行运行,初次编译可能会下一些本项目所依赖的包,需要一分多钟,后面编译会快很多,编译完成后会弹出一个浏览器的窗口(注意,这里建议使用Chrome浏览器,其他浏览器笔者没有测试过,按照官方的说法,目前支持最好的应该是Chrome浏览器)如下图:

手把手带你使用Flutter开发web应用程序(flutter web开发)

我们来看看项目结构:

手把手带你使用Flutter开发web应用程序(flutter web开发)

可以看到,大体的项目结构了普通的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( 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\’;

而普通Flutter项目导入的是:

import \’package:flutter/material.dart\’;

原则就是原来的 package:flutter 改为 package:flutter_web ,原来的 dart:ui 改为 package:flutter_web_ui/ui.dart,当然,这些你只需要知道就好了,实际生产的时候直接快捷键按下,编辑器会自动帮我们导入正确的包。

资源的使用

我们之前使用资源文件(比如图片)的方式是在根目录下新建一个资源文件夹,然后将资源文件放在资源文件夹下,然后在pubspec.yaml文件中进行文件路径的声明,然后就可以使用了,在Flutter for web中,我们需要将原来的资源文件夹从之前的项目根目录迁移到web文件夹下,就像这样:

手把手带你使用Flutter开发web应用程序(flutter web开发)

然后就可以正常使用了,这也是迄今为止我发现的Flutter for web和普通Flutter项目的不同之处了。

编写完布局文件后我们将main.dart稍作修改,引入我们的LoginPage:

import \’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在web端部署的流程,可以看到,目前Flutter在Web上的部署已经没有任何压力了,只是由于生态还不完整,很多库和包还不能用,所以目前还无法投入商用软件中,希望Flutter可以发展的越来越完善。同时,结合笔者个人的开发经验,建议大家开发Flutter项目时一定不要怕麻烦,多用像mvp这类的项目结构,这样可以大大提高开发效率。

关于Flutter for web的更多资料,可以参考Flutter官方的仓库:https://github.com/flutter/flutter_web。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

(0)
上一篇 2024年5月10日 上午9:04
下一篇 2024年5月10日 上午9:15

相关推荐