Api Calls

Satyam KumarSatyam Kumar
2 min read

Create a .env file in the root folder.

//Terminal
flutter pub get flutter_dotenv
flutter pub add

Open this file:
android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Now add .env file to assets

assets:
    - .env

Now in main.dart

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await dotenv.load(fileName: ".env");
    print('✅ API Key loaded: ${dotenv.env['API_KEY']}');

    runApp(const MyApp());
  } on EmptyEnvFileError catch (e) {
    print('❌ .env file is missing or empty: $e');
    runApp(const ErrorApp(message: 'Missing .env file.'));
  } catch (e, stack) {
    print('❌ Unexpected error: $e');
    print('Stack: $stack');
    runApp(const ErrorApp(message: 'Unexpected error.'));
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const Home(), //call your next page
    );
  }
}

class ErrorApp extends StatelessWidget {
  final String message;

  const ErrorApp({super.key, required this.message});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Startup Error',
      home: Scaffold(
        appBar: AppBar(title: const Text('Error'), backgroundColor: Colors.red),
        body: Center(
          child: Text(
            message,
            style: const TextStyle(fontSize: 18, color: Colors.red),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
}

Now Run the app

✅ API Key loaded:’api_ke ’ //if this gets printed in your console then you are in right path.

Now for Api call create a fetch function.

final key = dotenv.env['API_KEY'];
Map result = {};
Future<List> fetchApi() async {
  // var response = await http.get(
  //   'https://newsapi.org/v2/top-headlines?country=us&category=Technology&apiKey= $key',
  // );

  final uri = Uri.https('newsapi.org', '/v2/top-headlines', {
    'country': 'us',
    'category': 'technology',
    'q': searchhh.searchcontroller.text,
    'apiKey': key!,
  });
  try {
    final response = await http.get(uri);

    if (response.statusCode == 200) {
      // ✅ Parse JSON

      result = convert.jsonDecode(response.body);
      print(result);
    } else {
      print('❌ Error: ${response.statusCode}');
    }
  } catch (e) {
    print('❌ Exception: $e');
  }
  return (result['articles']);
}

Now call the initstate function in hompage.(This function will be the first functionto run when app starts).

 @override
  void initState() {
    super.initState();
    fetchApi(); 
  }x
0
Subscribe to my newsletter

Read articles from Satyam Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Satyam Kumar
Satyam Kumar