Flutter app 更新

Flutter 不支持 code-push。

在android 只能强制更新apk或者跳转到谷歌stop去下载。

在ios,只能提醒去 App Store 官网下载。

## 步骤一

- 创建一个 Updater 类。

-  获取线上最新的版本号与本地版本号。

-    通过字符串 hashCode 比较版本号是否一致。

-    如果不一致,那么弹出更新对话框。

-    更新提醒对话框我们一天弹出一次就好了。

-    如果用户点击更新,则跳转到对应的地址。



``` dart

class Updater extends StatefulWidget {

  const Updater({@required this.child, Key key}) : super(key: key);

  final Widget child;

  @override

  State createState() => UpdaterState();

}

class UpdaterState extends State {

  @override

  void initState() {

    super.initState();

    _checkForUpdates();

  }

  Future _checkForUpdates() async {

    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    String version = packageInfo.version;

    String updateUrl = Theme.of(context).platform == TargetPlatform.iOS

        ? updateUrlLs['ios']

        : updateUrlLs['android'];

    String updateTime = PreferModel.prefs.getString('updateTime') ?? null;

    /// 一天之内只提醒一次需要更新

    if (updateTime != null && DateTime.parse(updateTime).day == DateTime.now().day) {

      return;

    }

    try {

      Response response = await Dio().get(updateUrl);

      String versionShort = response.data['versionShort'];

      if (version.hashCode != versionShort.hashCode) {

        final bool wantsUpdate = await showDialog(

          context: context,

          builder: (BuildContext context) =>

              _buildDialog(context, response.data['update_url'], packageInfo, versionShort),

          barrierDismissible: false,

        );

        if (wantsUpdate != null && wantsUpdate) {

          PreferModel.prefs.remove('updateTime');

          launch(response.data['update_url'],

          forceSafariVC: false,

          );

        } else {

          PreferModel.prefs.setString('updateTime', DateTime.now().toString());

        }

      }

    } catch (e) {}

  }

  Widget _buildDialog(

      BuildContext context, String updateUrl, PackageInfo packageInfo, String versionShort) {

    final ThemeData theme = Theme.of(context);

    final TextStyle dialogTextStyle =

        theme.textTheme.subhead.copyWith(color: theme.textTheme.caption.color);

    return CupertinoAlertDialog(

      title: Text('是否立即更新${packageInfo.appName}?'),

      content: Text('检测到新版本 v$versionShort', style: dialogTextStyle),

      actions: [

        CupertinoDialogAction(

          child: const Text('下次再说'),

          onPressed: () {

            Navigator.pop(context, false);

          },

        ),

        CupertinoDialogAction(

          child: const Text('立即更新'),

          onPressed: () {

            Navigator.pop(context, true);

          },

        ),

      ],

    );

  }

  @override

  Widget build(BuildContext context) => widget.child;

}

```


你可能感兴趣的:(Flutter app 更新)