SQLite Blog in Flutter: First Part

We’re going to learn how we can build a SQLite Blog Application in Flutter. As it sounds, a Blog App must fulfill some criteria.

What are they?

The SQLite database should allow us to insert, update or delete data. Moreover, we need to retrieve data as well.

For better understanding, let’s break this flutter tutorial in a few parts.

So, in this first part will teach us to learn a couple of things.

Firstly, we’ll use a Flutter package or plugin, sqflite which is available in pub.dev.

Secondly, we also need to use Future API, async, await keywords, and then functions to make it successful.

We’ve discussed Future, await and async for absolute beginners in previous section, is Flutter single thread? Therefore, if you’re a beginner, you might take a look before we start.

Which database is best for Flutter?

The sqflite package provides classes and functions to interact with a SQLite database.

And, finally, we need a Text Controller to type on the screen. Right?

We also need a Text Button or Elevated Button to press, so that that piece of data will be inserted into the SQLite database.

To begin with, we need to add the dependencies in pubspec.yaml.

dependencies:
  cupertino_icons: ^1.0.2
  flutter:
    sdk: flutter
  flutter_staggered_grid_view: ^0.4.1
  intl: ^0.17.0
  path: 
  provider: ^6.0.1
  sqflite: 

After that, we need to use await and async in our entry point.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'view/all_pages.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  static const String title = 'Blogs';

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

  @override
  Widget build(BuildContext context) => MaterialApp(
        debugShowCheckedModeBanner: false,
        title: title,
        themeMode: ThemeMode.light,
        theme: ThemeData(
          primaryColor: Colors.pink.shade200,
          scaffoldBackgroundColor: Colors.pink.shade600,
          appBarTheme: const AppBarTheme(
            backgroundColor: Colors.transparent,
            elevation: 0,
          ),
        ),
        home: const AllPages(),
      );
}

In our Material App widget, we’ve defined the global theme. In addition, we pass that theme to our Home page AllPages.

Next, we need to define couple of things in this page, AllPages. If there is no data in our SQLite database, then it will show a page like below.

Home page of the Blog App in Flutter
Home page of the Blog App in Flutter

As a result, we can start adding blog items to this Flutter Application. However, in our Home page, AllPages stateful Widget, we must define that.

Let’s take a look at the AllPages code snippet.

import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import '/model/blogs.dart';
import '/model/blog.dart';
import 'edit.dart';
import 'detail.dart';
import '/controller/blog_card.dart';

class AllPages extends StatefulWidget {
  const AllPages({Key? key}) : super(key: key);

  @override
  _AllPagesState createState() => _AllPagesState();
}

class _AllPagesState extends State<AllPages> {
  late List<Blog> blogs;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();

    refreshingAllBogs();
  }

  @override
  void dispose() {
    BlogDatabaseHandler.instance.close();

    super.dispose();
  }

  Future refreshingAllBogs() async {
    setState(() => isLoading = true);

    blogs = await BlogDatabaseHandler.instance.readAllBlogs();

    setState(() => isLoading = false);
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: const Text(
            'Blogs',
            style: TextStyle(fontSize: 24),
          ),
          actions: [
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  onPrimary: Colors.white,
                  primary: Colors.pink.shade900,
                ),
                onPressed: () async {
                  await Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) => const EditPage()),
                  );

                  refreshingAllBogs();
                },
                child: const Text('Add Blog'),
              ),
            )
          ],
        ),
        body: Center(
          child: isLoading
              ? const CircularProgressIndicator()
              : blogs.isEmpty
                  ? const Text(
                      'No Blogs in the beginning...',
                      style: TextStyle(color: Colors.white, fontSize: 60),
                    )
                  : buildingAllBlogs(),
        ),
      );

  Widget buildingAllBlogs() => StaggeredGridView.countBuilder(
        padding: const EdgeInsets.all(8),
        itemCount: blogs.length,
        staggeredTileBuilder: (index) => const StaggeredTile.fit(2),
        crossAxisCount: 4,
        mainAxisSpacing: 4,
        crossAxisSpacing: 4,
        itemBuilder: (context, index) {
          final blog = blogs[index];

          return GestureDetector(
            onTap: () async {
              await Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => DetailPage(blogId: blog.id!),
              ));

              refreshingAllBogs();
            },
            child: BlogCard(blog: blog, index: index),
          );
        },
      );
}

The above Widget plays a very important role in our Flutter SQLite Blog Application.

Firstly, it would let us allow to add a new blog. To do that, this widget takes us to a different Widget, EditPage.

Inserting data into Blog App in Flutter
Inserting data into Blog App in Flutter

After that, once we are done in the EditPage, that again sends us back to this Widget, AllPages. And, here, we start seeing all the blogs.

Retrieving data in Blog App in Flutter
Retrieving data in Blog App in Flutter

Retrieving data from SQLite database is much easier than inserting data. However, we’ll learn everything from scratch here while building this Blog app in Flutter.

Meanwhile, with the help of Future API, async, await keywords, and then functions and FutureBuilder widget, we can do that.

At the same screen we also catch the data or list item that we’ve sent from the home page.

In the above code, we’ve found a couple of interesting thing.

Firstly, the home page imports couple of other pages and two model classes. The model classes provide the data models.

Secondly, the model class also serves as database handler utilities.

And, finally, we needed the edit page and the detail page to serve other purposes, such as updating and deleting items.

At the end, after finishing all tasks, we come back to the home page again.

This is the flow of logic that runs this SQLite Blog application in Flutter.

In the next section, we’ll take a look at how we can build the data model and database utilities with the help of sqflite package.

By that time, if you have interest, please visit the respective GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

2 responses to “SQLite Blog in Flutter: First Part”

  1. […] already started building the SQLite Blog application in Flutter. The previous section has discussed the application structure. In this second part, we’ll […]

  2. […] We’ve already built a significant part of a SQLite Blog Application in Flutter. We might also see the progress of the initial phase in this section – SQLite Blog application in Flutter. […]

Leave a Reply