ad
ad
Topview AI logo

flutter project | random quote generator using flutter

People & Blogs


Introduction

In this article, we will explore how to create a simple random quote generator application using Flutter. The application will fetch random quotes from an external API and display them in a user-friendly interface.

Step 1: Setting Up the Flutter Project

To start, create a new Flutter project named test_app. Once you have set up the project, navigate to the main.dart file where you'll find the default Flutter code.

Running the Default Application

Upon running the default application, you will see the standard Flutter layout. At this point, we will customize the application to suit our needs.

Creating the Code Generator Stateful Widget

Remove the default MyHomePage widget and related code. Instead, create a new Stateful widget named QuoteGenerator. Replace MyHomePage with QuoteGenerator in the home property of your MaterialApp.

class QuoteGenerator extends StatefulWidget (
  @override
  _QuoteGeneratorState createState() => _QuoteGeneratorState();
)

class _QuoteGeneratorState extends State<QuoteGenerator> (
  String quote = '';
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: [Text('Random Quote Generator')](https://www.topview.ai/blog/detail/html-css-javascript-project-random-quote-generator),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(quote.isEmpty ? 'Random Code' : quote, style: TextStyle(fontSize: 20)),
            SizedBox(height: 30),
            ElevatedButton(
              onPressed: generateQuote,
              child: Text('Generate'),
            ),
          ],
        ),
      ),
    );
  )
}

Adding the Generate Button

In the body of the Scaffold, we placed a Center widget that contains a Column. The column has a Text widget to display the quote, a SizedBox for spacing, and an ElevatedButton to generate new quotes.

Step 2: Fetching Data from the API

We will be using the http API from https://api.adviceslip.com/advice to fetch the random quotes. First, add the http dependency to your pubspec.yaml file and run flutter pub get to fetch the required package.

Importing the HTTP Package

Import the HTTP package at the top of your main.dart:

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

Implementing the Logic to Fetch Quotes

Create a method named generateQuote that fetches the quote when the button is pressed. Use http.get to retrieve data from the API and decode the JSON response.

Future<void> generateQuote() async (
  final response = await http.get(Uri.parse('https://api.adviceslip.com/advice'));
  if (response.statusCode == 200) {
    final result = json.decode(response.body);
    setState(() {
      quote = result['slip']['advice'];
    ));
  } else (
    throw Exception('Failed to load quote');
  )
}

Updating the UI with New Quotes

When a user clicks the generate button, the generateQuote function will be called, fetching and displaying a new quote in the Text widget.

Step 3: Finalizing the Application

To enhance the user experience, we can adjust the text size and styling.

Styling the Quote Text

You can adjust the font size of the displayed quote text as follows:

Text(quote.isEmpty ? 'Random Code' : quote, style: TextStyle(fontSize: 20))

When you run the application, you should now see a functional random quote generator. Each time you click "Generate," a new quote will be displayed.

Conclusion

In this article, we walked through the steps of building a simple Flutter application that retrieves random quotes from an external API. This project is a great way to get started with Flutter and understand how to work with HTTP requests and JSON data.


Keywords

Flutter, random quote generator, StatefulWidget, API, HTTP, JSON, development, user interface

FAQ

Q: What is Flutter?
A: Flutter is an open-source UI software development kit created by Google for building natively compiled applications for mobile, web, and desktop from a single codebase.

Q: How do I fetch data from an API in Flutter?
A: Use the http package to make network requests and retrieve data from APIs. You can then decode the JSON response using the dart:convert library.

Q: Where can I find the HTTP package?
A: You can find the HTTP package on pub.dev by searching for http or by adding it to your pubspec.yaml file.

Q: Can I customize the style of the displayed quotes?
A: Yes! You can customize the styling of text widgets in Flutter by using properties like style, fontSize, and fontWeight in the Text widget.

Q: What should I do if I encounter an error while fetching data?
A: First, check the URL and ensure that the API is accessible. If the error persists, review your code for any logical mistakes or debugging messages.