Hyejung
Hyejung

Reputation: 1272

Error while trying to load an asset: Flutter Web engine failed to fetch "assets/.env"

I have .env file and deployed flutter web with github workflow.

Since .env file is ignored by .gitignore I tried to add .env file manually by adding values to github Secret Actions and then writing script workflow.yml as below.

workflow.yml

      - 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

And I comment .env from pubspec.yml.

  assets:
    # - .env
    - assets/images/
    - assets/app_intro/
    - assets/app_screen/

If I don't treat this as comment, it throws error when deploying web with github as below error message.

Compiling lib/main.dart for the Web... No file or variants found for asset: .env. Error detected in pubspec.yaml:

And I use these secret values in my code as below.

   await dotenv.load();

    final supabaseUrl = dotenv.env["SUPABASE_URL"];
    final supabaseAnonKey = dotenv.env["SUPABASE_ANONKEY"];

    if (supabaseUrl == null || supabaseAnonKey == null) {
      throw Exception("Supabase URL or Anon Key is not provided");
    }

    await Supabase.initialize(
      url: supabaseUrl,
      anonKey: supabaseAnonKey,
    );

build is done successfully.

But when I open web, it throws error.

main.dart.js:9456 Error while trying to load an asset: Flutter Web engine failed to fetch "assets/.env". HTTP request succeeded, but the server responded with HTTP status 404.

I don't understand why it tried to fetch from assets/.env, not .env and how to resolve this issue.

Upvotes: 0

Views: 1549

Answers (1)

unacorn
unacorn

Reputation: 1022

you still need to include the dotenv file.

  1. rename '.env' to 'dotenv' (refer https://github.com/java-james/flutter_dotenv/issues/28)

  2. in your code where you load your dotenv file, specify the name of and location. e.g. await dotenv.load(fileName: "./dotenv")

  3. after you build (flutter build web), copy the dotenv file to build/web folder.

Upvotes: 0

Related Questions