Reputation: 606
Working on a Flutter project using Supabase as a backend. I am trying to store my API keys in a .env file at the root level of my project and then read them at compile time using the .stringFromEnvironment method, but this no longer works (I'm about 90% certain it worked last week set up the same way in a different project, but now Supabase is throwing an error).
main.dart
Future<void> main() async {
await Supabase.initialize(
url: Env.supabaseTestUrl,
anonkey: Env.supabaseTestKey,
);
runApp(const MainApp());
}
env.dart
abstract class Env {
Static String get supabaseTestUrl => String.fromEnvironment('SUPABASE_TEST_URL');
Static String get supabaseTestKey => String.fromEnvironment('SUPABASE_TEST_KEY');
}
.env
SUPABASE_TEST_URL=https://asdfalwekdfdwlkjgfdlkjdsf.supabase.co
SUPABASE_TEST_KEY=asdlkfadslgfkhasdlgkhasdlkj...
As mentioned above, this setup was copied from a project that worked last week, and as far as I know nothing else has changed, but Supabase gives the following error upon running the app:
Error: AuthException(message: Invalid argument(s): No host specified in
URI/auth/v1/token?grant_type=password, statusCode: null, errorCode: null)
I've restarted the Supabase instance and verified my URL and KEY are correct. What am I doing missing?
Upvotes: 0
Views: 21
Reputation: 1
Since String.fromEnvironment
is only for compile-time variables and not for reading files, your attempt to use it to get your API keys from a .env
file would not succeed. You can use the flutter_dotenv
package to resolve this.
1.In your pubspec.yaml
file, add the flutter_dotenv
package:
yaml:
Dependencies:
Flutter:
SDK: Flutter
flutter_dotenv: ^5.0.
Load.env to ur main
Future<void> main() async {await dotenv.load(fileName: ".env");
await Supabase.initialize(
url: dotenv.env['SUPABASE_TEST_URL']!,
anonKey: dotenv.env['SUPABASE_TEST_KEY']!,
);
runApp(const MainApp());
}
3.Update your env.dart file to use flutter_dotenv
abstract class Env {
static String get supabaseTestUrl => dotenv.env['SUPABASE_TEST_URL']!;
static String get supabaseTestKey => dotenv.env['SUPABASE_TEST_KEY']!;
}
4.Make sure your .env file is included in the assets section of your pubspec.yaml
.flutter:
assets:
- .env
Upvotes: 0