랭귀지/Flutter(플러터)
Flutter 변수를 공통으로 사용하려면?
유키공
2024. 10. 23. 03:29
final String apiKey = "my_api_key"; // API 키 를 공통변수로 사용하려면
lib/
├── config/
│ └── globals.dart
├── main.dart
└── other_files.dart
// lib/globals.dart
library my_project.globals;
final String apiKey = "fc1e3ad82010475381daf9846e627fdd";
// lib/main.dart
import 'package:flutter/material.dart';
import 'globals.dart' as globals;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('API 키 예제')),
body: Center(
child: ElevatedButton(
onPressed: () {
print('API 키: ${globals.apiKey}');
},
child: Text('API 키 출력'),
),
),
),
);
}
}
`my_project`는 여러분의 Flutter 프로젝트의 이름으로 대체해야 합니다. Flutter 프로젝트를 생성할 때 지정한 이름을 사용하면 됩니다.
예를 들어, 프로젝트 이름이 `my_app`이라면 아래와 같이 수정하면 됩니다:
```dart
// lib/globals.dart
library my_app.globals;
final String apiKey = "my_api_key";
```
확인 방법
1. 프로젝트 이름 확인: `pubspec.yaml` 파일을 열어 `name` 필드를 확인하면 프로젝트 이름을 확인할 수 있습니다.
2. 일관성 유지: `library` 이름은 다른 파일에서 이 변수를 import할 때 사용하는 네임스페이스이므로, 일관성을 유지하는 것이 중요합니다.
이렇게 프로젝트 이름으로 대체하면 됩니다!