updater.dart 2.12 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
8 9

import 'package:url_launcher/url_launcher.dart';
10

11
typedef Future<String> UpdateUrlFetcher();
12 13

class Updater extends StatefulWidget {
14
  const Updater({ @required this.updateUrlFetcher, this.child, Key key })
15 16
    : assert(updateUrlFetcher != null),
      super(key: key);
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

  final UpdateUrlFetcher updateUrlFetcher;
  final Widget child;

  @override
  State createState() => new UpdaterState();
}

class UpdaterState extends State<Updater> {
  @override
  void initState() {
    super.initState();
    _checkForUpdates();
  }

  static DateTime _lastUpdateCheck;
33
  Future<void> _checkForUpdates() async {
34 35
    // Only prompt once a day
    if (_lastUpdateCheck != null &&
36
        new DateTime.now().difference(_lastUpdateCheck) < const Duration(days: 1)) {
37
      return null; // We already checked for updates recently
38 39 40
    }
    _lastUpdateCheck = new DateTime.now();

41
    final String updateUrl = await widget.updateUrlFetcher();
42
    if (updateUrl != null) {
43
      final bool wantsUpdate = await showDialog<bool>(context: context, builder: _buildDialog);
44
      if (wantsUpdate != null && wantsUpdate)
45
        launch(updateUrl);
46 47 48
    }
  }

49
  Widget _buildDialog(BuildContext context) {
50 51 52
    final ThemeData theme = Theme.of(context);
    final TextStyle dialogTextStyle =
        theme.textTheme.subhead.copyWith(color: theme.textTheme.caption.color);
53
    return new AlertDialog(
54
      title: const Text('Update Flutter Gallery?'),
55 56 57
      content: new Text('A newer version is available.', style: dialogTextStyle),
      actions: <Widget>[
        new FlatButton(
58 59 60 61 62
          child: const Text('NO THANKS'),
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
63
        new FlatButton(
64 65 66 67 68 69 70
          child: const Text('UPDATE'),
          onPressed: () {
            Navigator.pop(context, true);
          },
        ),
      ],
    );
71 72 73
  }

  @override
74
  Widget build(BuildContext context) => widget.child;
75
}