updates.dart 2.12 KB
Newer Older
1 2 3 4 5 6
// 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';

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

import 'package:url_launcher/url_launcher.dart';
11 12 13 14

typedef Future<String> UpdateUrlFetcher();

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

  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;
  Future<Null> _checkForUpdates() async {
    // Only prompt once a day
    if (_lastUpdateCheck != null &&
37
        new DateTime.now().difference(_lastUpdateCheck) < const Duration(days: 1)) {
38 39 40 41
      return; // We already checked for updates recently
    }
    _lastUpdateCheck = new DateTime.now();

42
    final String updateUrl = await widget.updateUrlFetcher();
43
    if (updateUrl != null) {
44
      final bool wantsUpdate = await showDialog(context: context, child: _buildDialog());
45
      if (wantsUpdate != null && wantsUpdate)
46
        launch(updateUrl);
47 48 49 50 51 52 53
    }
  }

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

  @override
72
  Widget build(BuildContext context) => widget.child;
73
}