Simple Flutter App: Cat Facts app


This app fetches random cat facts from the cat facts api.

 How the App Works

  1. Launch the App:
    • The app starts with a prompt to press the button for a random cat fact.
  2. Fetch Fact:
    • When the “Get a Cat Fact” button is pressed:
      • A GET request is sent to the Cat Facts API.
      • The app extracts the fact from the API response and updates the _catFact variable.
  3. Display Fact:
    • The fetched fact is displayed on the screen.
  4. Handle Errors:
    • If the request fails or the API is unavailable, an appropriate error message is shown.

Code

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class CatFactsApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: CatFactsScreen(),
    );
  }
}

class CatFactsScreen extends StatefulWidget {
  @override
  _CatFactsScreenState createState() => _CatFactsScreenState();
}

class _CatFactsScreenState extends State<CatFactsScreen> {
  String _catFact = '';

  Future<void> fetchCatFact() async {
    final url = Uri.parse('https://catfact.ninja/fact');

    try {
      final response = await http.get(url);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          _catFact = data['fact']; // Extract the "fact" field from the response
        });
      } else {
        setState(() {
          _catFact = 'Failed to load cat facts.';
        });
      }
    } catch (e) {
      setState(() {
        _catFact = 'An error occurred while fetching cat facts.';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Random Cat Facts')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(
              onPressed: fetchCatFact,
              child: Text('Get a Cat Fact'),
            ),
            SizedBox(height: 20),
            Text(
              _catFact.isNotEmpty ? _catFact : 'Press the button to fetch a cat fact!',
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

Code Breakdown

1. Fetching Cat Facts

final url = Uri.parse('https://catfact.ninja/fact');
final response = await http.get(url);
  • URL: The https://catfact.ninja/fact endpoint returns a random cat fact in JSON format.
  • HTTP Request: Sends a GET request to fetch data from the API.
  • Response Handling:
    • If the statusCode is 200, the API returns a successful response.
    • Parse the JSON response and extract the fact field.

State Management

String _catFact = ''; // Holds the current cat fact

setState(() {
  _catFact = data['fact'];
});
  • The _catFact variable stores the fact fetched from the API.
  • setState(): Updates the _catFact value and refreshes the UI to display the fetched data.

User Interface

Button to Fetch Fact
ElevatedButton(
  onPressed: fetchCatFact,
  child: Text('Get a Cat Fact'),
)

Fact Display

Text(
  _catFact.isNotEmpty ? _catFact : 'Press the button to fetch a cat fact!',
  style: TextStyle(fontSize: 18),
)
  • If _catFact is not empty, it displays the fetched fact.
  • Otherwise, it shows a prompt for the user to press the button.

Scaffold

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Random Cat Facts')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(
              onPressed: fetchCatFact,
              child: Text('Get a Cat Fact'),
            ),
            SizedBox(height: 20),
            Text(
              _catFact.isNotEmpty ? _catFact : 'Press the button to fetch a cat fact!',
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}