4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter APIキーを別ファイルに設定してGitに上げない方法

Posted at

#APIキーをGitに上げたくない
こう言う場合、Flutterではどうしたらいいのでしょうか?

今回は僕が取った方法を紹介!

##configファイルを作成

main.dartと同じ階層にconfig.dartを作成して、以下のようにAPIの値を設定

lib/config.dart
const API_KEY = "aaaaaaaaaaaaaaaaaa";

##importして使う
今回は映画のAPI(TMDB API)からデータを取得する部分でやってみます。

dartではimportしたファイルの変数を、特に何もすることなくそのまま使えます!
${API_KEY}の部分がconfig.dartで設定した変数ということになります:blush:

import '../config.dart';

class TopScreen extends StatelessWidget {

  getMovies() async {
    final url =
        'https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}&language=en-US&page=1';
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body)['results'];
      if (extractedData == null) {
        print('nothing to get');
        return;
      }
      return extractedData;
    } catch (error) {
      print(error);
      throw (error);
    }
  }

// 省略

}

##.gitignoreにconfig.dartを追加

これでソース管理には含まれなくなりました。

# ↓これを追加
config.dart

# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/

# IntelliJ related
*.iml
*.ipr
*.iws
.idea/

# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/

# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/

# Web related
lib/generated_plugin_registrant.dart

# Symbolication related
app.*.symbols

# Obfuscation related
app.*.map.json

# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
4
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?