Flutter開發 APP版本更新
阿新 • • 發佈:2019-04-12
前言:
Flutter目前還不支援熱更新,點選“版本更新”的下載按鈕手動去更新APP。下面我簡單總結一下在Flutter新增“版本更新”的功能。
實現的步驟:
1.配置AndroidMenifest.xml檔案
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.在pubspec.yaml新增sdk
dependencies:
...
cupertino_icons: ^0.1.0
package_info: ^0.3.2+1
3..第一次開啟APP時執行"版本更新"的網路請求
class DashboardPageState extends State<DashboardPage>{ var serviceVersionCode; @override void initState() { super.initState(); _getNewVersionAPP();//"版本更新"的非同步請求 } //非同步請求 Future _getNewVersionAPP() async { String url = url; DioUtil.get(url).then((response) { if (response != null) { setState(() { var data = response.data; serviceVersionCode = data["versionCode"];//獲取伺服器的versionCode _checkVersionCode(); //升級app版本的方法 }); } }); } }
4.比較伺服器的版本號跟當前的版本號,來判斷要不要升級APP應用程式
void _checkVersionCode() { PackageInfo.fromPlatform().then((PackageInfo packageInfo) { var currentVersionCode = packageInfo.version;//獲取當前的版本號 //如果獲取伺服器的版本號比當前應用程式的版本號還高,那麼提示升級 if (serviceVersionCode > currentVersionCode) { _showNewVersionAppDialog();//彈出"版本更新"的對話方塊 } }); }
5.彈出“版本更新”對話方塊
Future<void> _showNewVersionAppDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: new Row(
children: <Widget>[
new Image.asset("images/ic_launcher_icon.png",
height: 35.0, width: 35.0),
new Padding(
padding: const EdgeInsets.fromLTRB(30.0, 0.0, 10.0, 0.0),
child: new Text("專案名稱",
style: dialogButtonTextStyle))
],
),
content: new Text(
'版本更新',
style: dialogTextStyle),
actions: <Widget>[
new FlatButton(
child: new Text('Later', style: dialogButtonTextStyle),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('DownLoad', style: dialogButtonTextStyle),
onPressed: () {
_goToGooglePlay();//到Google Play官網去下載APK
},
)
],
);
});
}
6.到Google Play官網去下載APK
void _goToGooglePlay() {
Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
return new CommonWebViewPage(
url:
"https://play.google.com/store/apps/details?id=專案包名");
}));
}
7.總結
當有新版本需要升級時,客戶端會"版本更新"彈出對話方塊,使用者點選下載的按鈕直接跳轉到Google Play官網去下載APK就可以。APP版本更新的功能已經實現,歡迎大家圍觀。如果有什麼疑問的話,可以留言聯絡我