Show install native app prompt in Flutter PWA

Viewed 34

What is the best way to show a prompt to install the native app on a Flutter PWA?

I found this guide https://developer.chrome.com/blog/app-install-banners-native/ but I am not sure where the Javascript should go or if this needs to be coded somehow in Flutter code.

I also thought of maybe building a dialog myself, but I don't find an easy way to generate a persisten dialog over the whole app that can be dismissed by the user

1 Answers

It can be done in both Javascript and Flutter. The Native App Install Prompt link provides criterias which must be met and instructions how to prompt.

Here is one way to accomplish it in Flutter.

BeforeInstallPrompt(
  child: HomeScreen(),
),
import 'dart:html';
import 'package:flutter/material.dart';

class BeforeInstallPrompt extends StatefulWidget {
  final Widget child;

  const BeforeInstallPrompt({Key? key, required this.child}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _BeforeInstallPrompt();
}

class _BeforeInstallPrompt extends State<BeforeInstallPrompt> {
  BeforeInstallPromptEvent? deferredPrompt;

  @override
  void initState() {
    window.addEventListener('beforeinstallprompt', (e) {
      e.preventDefault();
      setState(() {
        deferredPrompt = e as BeforeInstallPromptEvent;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      widget.child,
      if (deferredPrompt != null)
        Positioned(
          left: 8,
          bottom: 8,
          child: ElevatedButton(
            onPressed: () async {
              await _showPrompt();
            },
            child: const Text('Install'),
          ),
        )
    ]);
  }

  _showPrompt() async {
    await deferredPrompt?.prompt();
    await deferredPrompt?.userChoice;
    setState(() {
      deferredPrompt = null;
    });
  }
}
Related