[flutter] 플러터에서 앱 라이브러리 디렉토리 경로 가져오기

플러터(Flutter) 앱을 개발할 때, 앱 디렉토리 내에 있는 라이브러리 파일들의 경로를 가져와야 할 때가 있습니다. 이러한 경우, 아래의 방법을 사용하여 플러터에서 앱 라이브러리 디렉토리 경로를 가져올 수 있습니다.

앱 라이브러리 디렉토리 경로 가져오기

플러터 앱에서는 path_provider 패키지를 사용하여 파일 시스템 경로를 가져올 수 있습니다. 이 패키지를 사용하여 앱 라이브러리 디렉토리 경로를 가져오려면 다음 단계를 따르세요.

  1. path_provider 패키지를 pubspec.yaml 파일에 추가하세요. 아래와 같이 dependencies 섹션에 패키지를 추가합니다.
dependencies:
  flutter:
    sdk: flutter
  path_provider: ^2.0.2
  1. 패키지를 가져올 Dart 파일 상단에 다음을 추가하세요.
import 'package:path_provider/path_provider.dart';
  1. 앱 라이브러리 디렉토리 경로를 가져오려면 다음 코드를 사용하세요.
Directory appLibraryDir = await getApplicationDocumentsDirectory();
String appLibraryPath = appLibraryDir.path;

getApplicationDocumentsDirectory 함수를 사용하여 앱 라이브러리 디렉토리를 가져오고, path 속성을 사용하여 해당 경로를 가져옵니다.

완성된 코드 예시

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Directory? appLibraryDir;
  String? appLibraryPath;

  @override
  void initState() {
    super.initState();
    getAppLibraryPath();
  }

  Future<void> getAppLibraryPath() async {
    appLibraryDir = await getApplicationDocumentsDirectory();
    setState(() {
      appLibraryPath = appLibraryDir!.path;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('App Library Directory'),
        ),
        body: Center(
          child: Text(appLibraryPath ?? 'Loading...'),
        ),
      ),
    );
  }
}

위의 코드는 앱이 시작되면 getApplicationDocumentsDirectory 함수를 호출하여 앱 라이브러리 디렉토리 경로를 가져옵니다. 그리고 앱 바디에는 해당 경로를 표시하는 텍스트 위젯이 있습니다.

앱을 실행하면 화면에 앱 라이브러리 디렉토리 경로가 표시됩니다.

이제 플러터 앱에서 앱 라이브러리 디렉토리 경로를 가져오는 방법을 알게 되었습니다. 이를 통해 앱에서 필요한 파일들을 관리하고 활용할 수 있습니다.

참고