眾所周知Google對于Flutter的期望是全平臺統一UI開發,號稱要做一套“一份代碼、全平臺部署”的UI框架,這一點在移動端已經很成熟了,國內有很多成功的案例,典型的像阿里的閑魚客戶端,但是Flutter所聲稱的桌面端和Web端的相關案例還很少,之前我寫過一篇文章介紹如何將Flutter代碼部署成為桌面端程序,那么本文就該介紹如何將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操作系統為例:
cd
vim .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中新建項目,如下圖所示:
注意三點:
- 選擇Dart項目,而不是新建Flutter項目
- 正確設置自己dart sdk的位置
- 選擇Generate sample content中的Flutter Web App選項
創建完成后我們的項目就默認支持部署到Web了,在Idea中應該可以直接點擊運行按鈕進行運行,或者可以在Idea的終端中輸入:
wevdev serve
進行運行,初次編譯可能會下一些本項目所依賴的包,需要一分多鐘,后面編譯會快很多,編譯完成后會彈出一個瀏覽器的窗口(注意,這里建議使用Chrome瀏覽器,其他瀏覽器筆者沒有測試過,按照官方的說法,目前支持最好的應該是Chrome瀏覽器)如下圖:
我們來看看項目結構:
可以看到,大體的項目結構了普通的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 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可以發展的越來越完善。同時,結合筆者個人的開發經驗,建議大家開發Flutter項目時一定不要怕麻煩,多用像mvp這類的項目結構,這樣可以大大提高開發效率。
如果你喜歡 Flutter ,想自己嘗試一下的話,我收集了很多flutter的資料可以免費分享給大家!需要資料的小伙伴們可以加我的技術交流分享qq群:825106898。