Android Core

ListView using SQflite in Flutter – Todo Application

In this tutorial, we’ll take a look at how to create a ListView using Sqflite in Flutter. In the previous article on Sqflite in Flutter, we saw how to build a simple todo application using Sqflite.

Since then, I’ve gotten a lot of requests to create an article on how to build a listview using Sqflite. So, in this tutorial, I’ll extend the same application to build a listview using sqflite database.

If you haven’t checked out the previous article, I highly recommend doing it, as we’ll be building upon that article itself: Using SQLite in Flutter

Creating a new screen

Go ahead and create the application from the previous part here.

We’ll be adding one more screen to display the list of items added. It can be accessed via a button on the toolbar on the top. Create the button in your AppBar as shown below: 

1
2
3
4
5
6
7
8
9
appBar: AppBar(
  title: Text(widget.title),
  actions: <Widget>[
    IconButton(
      icon: Icon(Icons.favorite),
      onPressed: null,
    )
  ],
)

In order to add a new screen, first create a file called, favourite_screen.dart and create a stateful widget inside it:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
import 'package:flutter/material.dart';
 
 
class FavouritesScreen extends StatefulWidget {
  static const routeName = '/favourites';
 
  @override
  _FavouritesScreenState createState() => _FavouritesScreenState();
}
 
class _FavouritesScreenState extends State<FavouritesScreen> {
 
 
}

Setting up Navigation

Now, setting up navigation is a whole another post in itself, but we’ll focus this article on creating a ListView using Sqflite only. So, just setup the navigation as shown below inside your MaterialApp widget in main.dart

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Listify'),
      routes: {
        FavouritesScreen.routeName: (ctx) => FavouritesScreen(), // setting up routes
      },
    );
  }
}

Now whenever the user clicks on the favourites button on the top, we’ll navigate to the screen as shown:

1
2
3
4
5
IconButton(
  icon: Icon(Icons.favorite),
  onPressed: () =>
      Navigator.of(context).pushNamed(FavouritesScreen.routeName),
)

Fetching data from Sqflite

Now comes the meaty part. We’ve to get the data from the Sqflite database and populate in the listview. For fetching the data we’ll use SqliteDatabaseHelper from the previous tutorial.

The best place to get the data is inside the initState method. This is where the setup should happen before the screen is painted. We’ll store the data in a class property called taskList.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
class _FavouritesScreenState extends State<FavouritesScreen> {
  List<Todo> taskList = new List();
 
  @override
  void initState() {
    super.initState();
 
    DatabaseHelper.instance.queryAllRows().then((value) {
      setState(() {
        value.forEach((element) {
          taskList.add(Todo(id: element['id'], title: element["title"]));
        });
      });
    }).catchError((error) {
      print(error);
    });
  }
 
...

Creating the ListView

To create the ListView using Sqflite we’ll be using the builder pattern. Here’s how we do it: 

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Favourites"),
    ),
    body: Container(
      child: ListView.builder(itemBuilder: (ctx, index) {
        if (index == taskList.length) return null;
        return ListTile(
          title: Text(taskList[index].title),
          leading: Text(taskList[index].id.toString()),
        );
      }),
    ),
  );
}

You can also choose to display something else in case the list is empty, but here we’ll just stick to the non-empty case.

Let’s go ahead and test our application:

So that’s it. It’s really easy to create a listview us sqflite in flutter. Let me know if you still run into any issues, in the comments section below

Published on Java Code Geeks with permission by Ayusch Jain, partner at our JCG program. See the original article here: ListView using SQflite in Flutter – Todo Application

Opinions expressed by Java Code Geeks contributors are their own.

Ayusch Jain

Ayusch is a Software Engineer currently working in Android Development. He's worked long enough that he's transformed into an Android himself :P. Additionally, he also maintains a community of Android developers called: AndroidVille and writes about Android on his website: https://ayusch.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button