How to use secret key of env file in main.dart when deploying flutter web with flutter actions?

50 Views Asked by At

I deployed flutter web page with github actions.

I created workflow.yml in .github/workflows/workflow.yml.

name: gh-pages

on:
  push:
    branches: [main]
jobs:
  build:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2
      - uses: subosito/flutter-action@v1
      - uses: bluefireteam/flutter-gh-pages@v7
        with:
          baseHref: /onldocc_admin/

But the problem is that It deploys web site based on repository of github.

I can't ignore .env file. If so, deployment fails.

So I've found many sources and people say to use secret actions.

  • Github > Settings > Secrets and variables > Actions I set Repository Secrets as below.

enter image description here

And mostly people elaborate how to use this key in workflow like below.

name: gh-pages

on:
  push:
    branches: [main]
jobs:
  build:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2
      - uses: subosito/flutter-action@v1
      - uses: bluefireteam/flutter-gh-pages@v7
        with:
          baseHref: /onldocc_admin/
      - name: Create.env
        shell: bash
        env:
          SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
          SUPABASE_ANONKEY: ${{ secrets.SUPABASE_ANONKEY }}
        run: |
          touch .env
          echo SUPABASE_URL=${{ secrets.SUPABASE_URL }} > .env
          echo SUPABASE_ANONKEY=${{ secrets.SUPABASE_ANONKEY }} > .env
          cat .env

But my questions is I have to use these secret keys in main.dart in flutter project.

    final supabaseUrlDebug = dotenv.env["SUPABASE_URL"];
    final supabaseAnonKeyDebug = dotenv.env["SUPABASE_ANONKEY"];

    await Supabase.initialize(
      url: supabaseUrlDebug!,
      anonKey: supabaseAnonKeyDebug!,
    );

And I need to replace dotenv.env["SUPABASE_URL"] to something else, maybe fetching from secret keys from secret repository.

But I can't find this way anywhere!!

If I upload env file, this is too critical on security issue.

Probably there should be any way to solve this..

Please help me.

1

There are 1 best solutions below

2
Alyana Mahesh On

use env.json file instead, and while running the application with flutter run use the flag --dart-define-from-file=env.json

In your case:
replace your .env file with

- touch env.json
- echo '{
  "SUPABASE_ANONKEY" : "${{ secrets.SUPABASE_URL }}",
  "SUPABASE_URL" : "${{ secrets.SUPABASE_ANONKEY }}"
}' > env.json

env.json will look something like

{
  "SUPABASE_ANONKEY" : "<YOUR_SUPABASE_ANONKEY>",
  "SUPABASE_URL" : "<SUPABASE_URL>"
}

In code use
String.fromEnvironment('SUPABASE_ANONKEY')
String.fromEnvironment('SUPABASE_URL')

finally, add this to run the application.

flutter run --dart-define-from-file=env.json