패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.10.2

restart_app

플랫폼별 네이티브 동작을 사용하여 플러터 앱을 재시작하거나 다시 시작하는 플러터 플러그인입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
18만
좋아요
531
Pub 점수
160

패키지 설치

flutter pub add restart_app

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

restart_app 패키지는 네이티브 플랫폼 동작을 따르는 방식으로 Flutter 애플리케이션을 재시작하거나 다시 시작하는 간단한 방법을 제공합니다. 개발자는 안드로이드, iOS, 웹, macOS, Windows, 리눅스에서 앱을 프로그래밍 방식으로 재시작할 수 있으며, 다양한 플랫폼 간 일관된 사용자 경험을 보장합니다. 이 플러그인은 시스템 레벨의 앱 재시작이나 브라우저 새로 고침과 같은 플랫폼별 메커니즘을 활용하여 테마 전환, 언어 변경, 구성 업데이트와 같이 앱 전체를 새로 고쳐야 하는 상황에 이상적입니다. 가볍고 기존 프로젝트에 쉽게 통합할 수 있습니다.

사용 사례

  • 앱 테마 다시 로드
  • 언어 변경은 재시작이 필요합니다
  • 구성 업데이트 처리
  • 사용자 세션 재설정됨
  • 디버깅 및 개발 워크플로우

주요 기능

  • 크로스 플랫폼 재시작 지원
  • 네이티브 플랫폼 동작
  • 간단한 API 통합
  • 추가 권한이 필요하지 않습니다
  • 모바일, 데스크톱 및 웹에서 작동합니다

적합한 대상

  • 앱 재시작 기능이 필요한 개발자
  • 동적 UI 설정을 가진 앱
  • 다국어 애플리케이션
  • 개발 도구 및 디버그 유틸리티

고려 사항

  • 모든 웹 환경에서 작동하지 않을 수 있습니다
  • 상태 지속성 처리가 적절히 이루어져야 합니다
  • 즉시 상태 전환에 적합하지 않음
  • 재시작 시점에 대한 제어가 제한됨
  • 플랫폼별 제한 사항이 적용될 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

restart_app

pub package likes popularity pub points

Restart or relaunch your Flutter app from Dart with one call.

Each platform uses the safest supported restart path available to Flutter apps. See the published docs for guides, reference, and deployment details. The platform behavior guide covers the exact native mechanism on each target.

Quick start

Add the dependency:

dependencies:
  restart_app: ^1.9.1

Import and call:

import 'package:restart_app/restart_app.dart';

await Restart.restartApp();

If you need to handle errors:

final result = await Restart.restartApp();

if (!result.success) {
  // Show or log result.code and result.message.
}

Restart.restartApp() is the restart API. It returns a RestartResult with success, the resolved mode, and platform error details when the restart cannot be started.

Customization

Default behavior works for normal app restart flows. Pass options only when your app needs a specific platform behavior.

await Restart.restartApp(
  mode: RestartMode.platformDefault,
  webOrigin: '#/home',
  forceKill: false,
  notificationTitle: 'Restart',
  notificationBody: 'Tap to reopen the app.',
);

Parameters

Parameter Platform Description
mode All Requested restart behavior: platformDefault, flutterEngine, process, or notificationFallback.
webOrigin Web Custom URL for the reload. When null, the current page reloads and keeps its route. Supports hash strategy (e.g. '#/home').
notificationTitle iOS Title of the local notification shown only when mode is notificationFallback. Defaults to Restart.
notificationBody iOS Body of the local notification shown only when mode is notificationFallback. Defaults to Tap to reopen the app.
forceKill Android When true, fully terminates the process after launching the new activity. Defaults to false. RestartMode.process enables this path automatically on Android.

Platform behavior

Platform Mechanism Limitations
Android Relaunches the main activity via PackageManager. Supports Android TV and Fire TV via leanback launcher fallback. RestartMode.process and forceKill: true kill the process after launch for a clean cold start. None
iOS Recommended: opt-in Flutter engine restart that creates a new FlutterEngine, runs Dart again, re-registers plugins, and replaces the root FlutterViewController in the same iOS process. Legacy: local notification + exit(0) + user tap. iOS has no public API for automatic full process restart. Engine restart is not a process restart and cannot reset native singleton state. Legacy fallback requires notification permission and user action.
Web Reloads the page using window.location. None
macOS Launches a new instance via NSWorkspace and terminates the current process. Sandboxed (Mac App Store) builds cannot launch new instances of themselves. Returns a failed result in this case.
Linux Replaces the current process via execv. Fully automatic. None
Windows Launches a new instance via CreateProcess and terminates the current process. MSIX-packaged (Microsoft Store) apps cannot be relaunched via CreateProcess.

iOS

iOS does not provide a public API for an app to terminate itself and automatically launch a fresh process of the same app. Android-style full process restart is not available on iOS with public APIs.

restart_app supports two iOS behaviors:

  1. Flutter engine restart, recommended. This keeps the iOS process alive, creates a new FlutterEngine, runs the Dart entrypoint again, re-registers plugins through the host app's GeneratedPluginRegistrant, creates a new FlutterViewController, replaces the active root view controller, and destroys the old engine context.
  2. Notification fallback, legacy and explicit only. This schedules a local notification, calls exit(0), and requires the user to tap the notification to reopen the app. This is not a true restart and is not recommended as normal product behavior.
Configure Flutter engine restart

The host app owns GeneratedPluginRegistrant, so iOS engine restart requires one app-side setup step.

Choose the snippet that matches your iOS lifecycle.

Flutter 3.41+ UIScene apps

Use this shape when your app has migrated to Flutter's UIScene lifecycle and your delegate already looks like @objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate.

Keep the normal plugin registration for the implicit app engine in didInitializeImplicitFlutterEngine. Add RestartAppPlugin.configureEngineRestart in application(_:didFinishLaunchingWithOptions:) so restart_app can register plugins on each newly created engine:

import UIKit
import Flutter
import restart_app

@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    RestartAppPlugin.configureEngineRestart { engine in
      GeneratedPluginRegistrant.register(with: engine)
    }

    return super.application(
      application,
      didFinishLaunchingWithOptions: launchOptions
    )
  }

  func didInitializeImplicitFlutterEngine(
    _ engineBridge: FlutterImplicitEngineBridge
  ) {
    GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
  }
}

This follows Flutter's UIScene migration model: the initial engine is registered through didInitializeImplicitFlutterEngine, and restarted engines are registered through the restart_app callback above.

restart_app automatically looks for the active foreground UIWindowScene and replaces that scene's key window root FlutterViewController. If your app has multiple scenes or a custom native shell, pass a windowProvider or viewControllerInstaller to configureEngineRestart so the plugin targets the correct window.

If you implement your own SceneDelegate, keep Flutter's scene lifecycle wiring there too: subclass FlutterSceneDelegate or conform to FlutterSceneLifeCycleProvider, as described in Flutter's UISceneDelegate migration guide.

Classic AppDelegate apps

Use this shape only when your app still registers plugins from application(_:didFinishLaunchingWithOptions:).

In ios/Runner/AppDelegate.swift:

import UIKit
import Flutter
import restart_app

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    RestartAppPlugin.configureEngineRestart { engine in
      GeneratedPluginRegistrant.register(with: engine)
    }

    GeneratedPluginRegistrant.register(with: self)

    return super.application(
      application,
      didFinishLaunchingWithOptions: launchOptions
    )
  }
}

Then call:

final result = await Restart.restartApp();

RestartMode.platformDefault uses Flutter engine restart on iOS when this setup is present. If this setup is missing, platformDefault fails cleanly on iOS instead of falling back to notification + exit(0).

To request the engine path explicitly:

final result = await Restart.restartApp(
  mode: RestartMode.flutterEngine,
);
iOS capabilities
final capability = await Restart.restartCapability();

if (capability.flutterEngineRestart) {
  await Restart.restartApp(mode: RestartMode.flutterEngine);
}
What iOS engine restart resets

It resets:

  • Dart root isolate
  • Flutter widget tree
  • Flutter engine-owned platform channels
  • Flutter plugin registrations for the new engine
  • Platform-view factory registrations for the new engine

It does not reset:

  • The iOS process
  • Swift, Objective-C, C, or C++ static/global state
  • Native singleton state
  • Native resources retained by plugins
  • Unrelated Flutter engines or background isolates
  • Native app launch lifecycle callbacks from a real process launch

For code-push systems and plugins with heavy native state, verify behavior in a real release build. Same-process engine restart is not equivalent to full process restart.

Legacy notification fallback

Use the notification fallback only when the tradeoff is acceptable:

Restart.restartApp(
  mode: RestartMode.notificationFallback,
  notificationTitle: 'Update applied',
  notificationBody: 'Tap to reopen the app.',
);

The plugin requests notification permission at the moment of restart. If not already granted, iOS shows the system prompt right before exit, which feels abrupt.

Request permission earlier in your app's lifecycle. The permission_handler package works well for this.

If notification permission has been denied, restartApp() returns a failed result.

Provisioning profiles

restart_app uses local notifications only, not push notifications. It adds no push-related entitlements to your app.

If you see "requires a provisioning profile with the Push Notifications feature" when exporting an IPA, another dependency is the cause (commonly firebase_messaging). Add the Push Notifications capability to your distribution provisioning profile.

Linux

Command-line arguments

By default, the restarted process launches without the original command-line arguments. To preserve them, call restart_app_plugin_store_argv in your linux/main.cc before running the Flutter engine:

#include <restart_app/restart_app_plugin.h>

int main(int argc, char** argv) {
  restart_app_plugin_store_argv(argc, argv);
  // ... rest of main()
}

Most Flutter apps don't rely on command-line arguments, so this step is optional.

Background isolates

Restart.restartApp() uses a platform channel and must run on the main isolate. Calling it from a background isolate throws:

Bad state: The BackgroundIsolateBinaryMessenger.instance value is invalid
until BackgroundIsolateBinaryMessenger.ensureInitialized is executed.

Send a message from your isolate to the main isolate instead:

// Main isolate: listen for restart signals
final receivePort = ReceivePort();
receivePort.listen((message) {
  if (message == 'restart') {
    Restart.restartApp();
  }
});

// Spawn the isolate with the SendPort
await Isolate.spawn(myIsolateFunction, receivePort.sendPort);

// Background isolate: signal instead of calling restartApp() directly
void myIsolateFunction(SendPort sendPort) {
  // ... your background work ...
  sendPort.send('restart');
}

Requirements

Dart SDK: >=3.4.0 · Flutter: >=3.22.0

Platform Minimum
Android minSdk 21, Java 17, Android Gradle Plugin 8 or 9
iOS 12.0
macOS 10.15

The Android module builds on Android Gradle Plugin 8 and 9. It applies the Kotlin Gradle Plugin only when nothing else has already provided Kotlin, so it builds on both AGP majors with the Flutter template default android.builtInKotlin=false. Turning built-in Kotlin on is a separate Flutter migration that needs Flutter 3.47 or later; on earlier Flutter releases it fails for every plugin, including Flutter's own plugin template.

Author

Created by Soroush Yousefpour

Buy Me A Book

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트