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.
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.
Upon running the default application, you will see the standard Flutter layout. At this point, we will customize the application to suit our needs.
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'),
),
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'),
),
],
),
),
);
)
}
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.
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.
Import the HTTP package at the top of your main.dart
:
import 'package:http/http.dart' as http;
import 'dart:convert';
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');
)
}
When a user clicks the generate button, the generateQuote
function will be called, fetching and displaying a new quote in the Text
widget.
To enhance the user experience, we can adjust the text size and styling.
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.
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.
Flutter, random quote generator, StatefulWidget, API, HTTP, JSON, development, user interface
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.
In addition to the incredible tools mentioned above, for those looking to elevate their video creation process even further, Topview.ai stands out as a revolutionary online AI video editor.
TopView.ai provides two powerful tools to help you make ads video in one click.
Materials to Video: you can upload your raw footage or pictures, TopView.ai will edit video based on media you uploaded for you.
Link to Video: you can paste an E-Commerce product link, TopView.ai will generate a video for you.