You are currently viewing How To Make Flutter Desktop App Single Instance?

How To Make Flutter Desktop App Single Instance?

Introduction

How to make Flutter desktop app single instance and why? Different use cases exist such as for security, integrity and to prevent many undesirable scenarios. Whatever your use case may be today we will learn how to make your Flutter desktop app single instance, So without any further delay let’s get straight to it.

Getting Started

  • Go to your project’s pubspec.yaml and add the following dependency
    flutter_single_instance: ^0.0.1
  • Navigate to main.dart and import the package we just installed
    import 'package:flutter_single_instance/flutter_single_instance.dart';
  • In the same main.dart file import dart’s io library
    import 'dart:io';

Making The App Single Instance

Since we have already imported all the libraries. Copy and Paste the following code in place of existing void main() and adjust it according to your needs

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (await FlutterSingleInstance.platform.isFirstInstance()) {
    runApp(const MainApp());
  } else {
    exit(0);
  }
}

Explanation

  • WidgetsFlutterBinding.ensureInitialized() is called whenever native code must run before running the flutter app this is a requirement of flutter_single_instance package. You can read more about the function here on Flutter’s official documentation
  • await FlutterSingleInstance.platform.isFirstInstance() is the part that handles the app instance logic and decides whether this is the first instance of the app or not
  • In case there is already a running instance else block handles it by terminating the app gracefully

Build The Project

From the terminal of your preference go to the root directory of your project and build it for any desktop platform. In this case we will build it for windows using the following command

flutter build windows

🧪 Testing The Build

After building the release build this is the final result

As evident from the video above clicking on the executable does not open any other instances and the Flutter Desktop app has single instance.

📝 Conclusion

Today we learned how to utilize the flutter_single_instance package from pub.dev to make our desktop applications single instance. We simply imported the package and with the help of one if statement managed to ensure that only one instance of the app will run at a time. That’s it for this post, if this post was helpful to you, you may like my other posts in the Flutter Archives. Thank you for reading.