Create Quote App in Flutter

Create Free Backend With Appwrite

Introduction

In this section, you will learn to create a quote app using online JSON in flutter. Before we start, make sure you have basic knowledge of JSON. If you don’t know start from here.

You can use JSON file from here. It contains 50+ quotes. Here is preview for first 3 quotes.

[
  {
    "text": "The only people who never fail are those who never try.",
    "from": "Ilka Chase"
  },
  {
    "text": "Failure is just another way to learn how to do something right.",
    "from": "Marian Wright Edelman"
  },
  {
    "text": "I failed my way to success.",
    "from": "Thomas Edison"
  },
]

How to Create Quote App

Now you will learn to create a quote app using online JSON. Here are the steps to create a app:

Step 1: Install http Package

To use online JSON in your app, the first step is to add the http package in your project. Open terminal at your project folder and execute the following command:

flutter pub add http
Step 2: Import the http Package

Now, you need to import the http package in your flutter application. To import the http package, open your main.dart file and add the following import statement:

import 'package:http/http.dart' as http;
Step 3: Create Model Class

Now, you need to create a model class for the JSON data. Create a new file called quote.dart inside lib folder and add the following code in it:

class Quote {
  final String text;
  final String from;

  // Constructor
  Quote({required this.text, required this.from});

  // Convert JSON to Quote Object
  factory Quote.fromJson(Map<String, dynamic> json) {
    return Quote(
      text: json['text'],
      from: json['from'],
    );
  }
}
Step 4: Load and Decode the JSON File

Now create a new file called onlineservice.dart inside lib folder and add the following code in it:

import 'dart:convert';
import 'quote.dart';

class OnlineService {
  // Load and Decode JSON
  Future<List<Quote>> getQuotes() async {
    // Load JSON
    final response = await http.get(Uri.parse('https://jsonguide.technologychannel.org/quotes.json'));

    // Decode JSON
    final json = jsonDecode(response.body).cast<Map<String, dynamic>>();

    // Convert JSON to Quote
    return json.map<Quote>((json) => Quote.fromJson(json)).toList();
  }
}
Step 5: Create Quote Widget

Now, you need to create a widget to display the quote. Create a new file called quote_widget.dart inside lib folder and add the following code in it:

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

class QuoteWidget extends StatelessWidget {
  final Quote quote;

  const QuoteWidget({Key? key, required this.quote}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 4,
      margin: const EdgeInsets.all(8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              quote.text,
              style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Text(
              '- ${quote.from}',
              style: const TextStyle(fontSize: 16, fontStyle: FontStyle.italic),
              textAlign: TextAlign.right,
            ),
          ],
        ),
      ),
    );
  }
}
Step 6: Display the JSON Data

Now, you can use the OnlineService class to display the JSON data. Here is how you can use it on your main.dart file:

import 'package:flutter/material.dart';
import 'onlineservice.dart';
import 'quote.dart';
import 'quote_widget.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: FutureBuilder<List<Quote>>(
          future: OnlineService().getQuotes(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            }
            if (snapshot.hasData) {
              final quotes = snapshot.data!;
              return ListView.builder(
                itemCount: quotes.length,
                itemBuilder: (context, index) {
                  return QuoteWidget(quote: quotes[index]);
                },
              );
            }
            return const Center(child: Text('No data available'));
          },
        ),
      ),
    );
  }
}
Run Online

Challenge

Now create a similar app using local JSON. You can use JSON file from here.