Introduction

The guide will show building a listview in Flutter dynamic. We will try to create a simple application using Flutter that is integrated with the SQLite database. You can try this tutorial with the following example step by step. Before that, you can read other articles with a database connection to Flutter.
First, we must create a project using Visual Studio Code software with the name "recyclerview". Here's how to create a new project using Visual Studio Code:
  1. Select View > Command Palette.
  2. Type "flutter", and select the Flutter: New Project.
  3. Enter a project name, such as "recyclerview", and press Enter.
  4. Create or select the parent directory for the new project folder with the name "recyclerview".
  5. Wait for project creation to complete and the main.dart file to appear, the project will be created with the name "recyclerview".
How To Create Listview in Flutter Dynamic
After that, create the database file in the directory application that was created. (e.g [projectname]/data/[databasename].db.
We must prepare the file database using SQLite. All we have to do is create a file with the .db extension first.
How To Create Listview in Flutter Dynamic
Edit the file pubspec.yaml in your directory, which should look something like:
  1. name: recyclerview
  2. description: A new Flutter project.
  3. # The following defines the version and build number for your application.
  4. # A version number is three numbers separated by dots, like 1.2.43
  5. # followed by an optional build number separated by a +.
  6. # Both the version and the builder number may be overridden in flutter
  7. # build by specifying --build-name and --build-number, respectively.
  8. # In Android, build-name is used as versionName while build-number used as versionCode.
  9. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning
  10. # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
  11. # Read more about iOS versioning at
  12. # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
  13. version: 1.0.0+1
  14. environment:
  15. sdk: ">=2.1.0 <3.0.0"
  16. dependencies:
  17. flutter:
  18. sdk: flutter
  19. # The following adds the Cupertino Icons font to your application.
  20. # Use with the CupertinoIcons class for iOS style icons.
  21. cupertino_icons: ^0.1.2
  22. english_words: ^3.1.0
  23. sqflite: any
  24. path_provider: ^0.4.0
  25. dev_dependencies:
  26. flutter_test:
  27. sdk: flutter
  28. # For information on the generic Dart part of this file, see the
  29. # following page: https://www.dartlang.org/tools/pub/pubspec
  30. # The following section is specific to Flutter.
  31. flutter:
  32. # The following line ensures that the Material Icons font is
  33. # included with your application, so that you can use the icons in
  34. # the material Icons class.
  35. uses-material-design: true
  36. assets:
  37. - data/flutter.db
  38. # To add assets to your application, add an assets section, like this:
  39. # assets:
  40. # - images/a_dot_burr.jpeg
  41. # - images/a_dot_ham.jpeg
  42. # An image asset can refer to one or more resolution-specific "variants", see
  43. # https://flutter.dev/assets-and-images/#resolution-aware.
  44. # For details regarding adding assets from package dependencies, see
  45. # https://flutter.dev/assets-and-images/#from-packages
  46. # To add custom fonts to your application, add a fonts section here,
  47. # in this "flutter" section. Each entry in this list should have a
  48. # "family" key with the font family name, and a "fonts" key with a
  49. # list giving the asset and other descriptors for the font. For
  50. # example:
  51. # fonts:
  52. # - family: Schyler
  53. # fonts:
  54. # - asset: fonts/Schyler-Regular.ttf
  55. # - asset: fonts/Schyler-Italic.ttf
  56. # style: italic
  57. # - family: Trajan Pro
  58. # fonts:
  59. # - asset: fonts/TrajanPro.ttf
  60. # - asset: fonts/TrajanPro_Bold.ttf
  61. # weight: 700
  62. #
  63. # For details regarding fonts from package dependencies,
  64. # see https://flutter.dev/custom-fonts/#from-packages

Next, we're going to need to create an entity class with the name fruit.dart in directory [projectname]/lib/, which helps us manage a fruit's data.
  1. class Fruits {
  2. int _id;
  3. String _name;
  4. Fruits(this._name);
  5. Fruits.fromMap(dynamic obj) {
  6. this._name = obj['name'];
  7. }
  8. String get name => _name;
  9. Map<String, dynamic> toMap() {
  10. var map = new Map<String, dynamic>();
  11. map["name"] = _name;
  12. return map;
  13. }
  14. }
And also create a database helper class, database_helper.dart
  1. import 'dart:io';
  2. import 'dart:typed_data';
  3. import 'package:flutter/services.dart';
  4. import 'package:recyclerview/fruit.dart';
  5. import 'package:path/path.dart';
  6. import 'dart:async';
  7. import 'package:path_provider/path_provider.dart';
  8. import 'package:sqflite/sqflite.dart';
  9. class DatabaseHelper {
  10. static final DatabaseHelper _instance = new DatabaseHelper.internal();
  11. factory DatabaseHelper() => _instance;
  12. static Database _db;
  13. Future<Database> get db async {
  14. if (_db != null) {
  15. return _db;
  16. }
  17. _db = await initDb();
  18. return _db;
  19. }
  20. DatabaseHelper.internal();
  21. initDb() async {
  22. Directory documentDirectory = await getApplicationDocumentsDirectory();
  23. String path = join(documentDirectory.path, "data_flutter.db");
  24. // Only copy if the database doesn't exist
  25. //if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound){
  26. // Load database from asset and copy
  27. ByteData data = await rootBundle.load(join('data', 'flutter.db'));
  28. List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
  29. // Save copied asset to documents
  30. await new File(path).writeAsBytes(bytes);
  31. //}
  32. var ourDb = await openDatabase(path);
  33. return ourDb;
  34. }
  35. }
After we create database_helper.dart, create a file for the query to get data fruits. The file is called query.dart
  1. import 'package:recyclerview/fruit.dart';
  2. import 'dart:async';
  3. import 'package:recyclerview/database_helper.dart';
  4. class QueryCtr {
  5. DatabaseHelper con = new DatabaseHelper();
  6. Future<List<Fruits>> getAllFruits() async {
  7. var dbClient = await con.db;
  8. var res = await dbClient.query("fruits");
  9. List<Fruits> list =
  10. res.isNotEmpty ? res.map((c) => Fruits.fromMap(c)).toList() : null;
  11. return list;
  12. }
  13. }
Later, we create main.dart
  1. import 'package:flutter/material.dart';
  2. import 'package:recyclerview/fruit.dart';
  3. import 'package:recyclerview/query.dart';
  4. void main() => runApp(new MyApp());
  5. class MyApp extends StatelessWidget {
  6. @override
  7. Widget build(BuildContext context) {
  8. return new MaterialApp(
  9. title: "List in Flutter",
  10. home: new Scaffold(
  11. appBar: new AppBar(
  12. title: Text("List"),
  13. ),
  14. body: RandomFruits(),
  15. ),
  16. );
  17. }
  18. }
  19. class RandomFruits extends StatefulWidget {
  20. @override
  21. State<StatefulWidget> createState() {
  22. return new RandomFruitsState();
  23. }
  24. }
  25. class RandomFruitsState extends State<RandomFruits> {
  26. final _biggerFont = const TextStyle(fontSize: 18.0);
  27. QueryCtr _query = new QueryCtr();
  28. @override
  29. Widget build(BuildContext context) {
  30. return Scaffold (
  31. appBar: AppBar(
  32. title: Text('Load data from DB'),
  33. ),
  34. body: FutureBuilder<List>(
  35. future: _query.getAllFruits(),
  36. initialData: List(),
  37. builder: (context, snapshot) {
  38. return snapshot.hasData ?
  39. new ListView.builder(
  40. padding: const EdgeInsets.all(10.0),
  41. itemCount: snapshot.data.length,
  42. itemBuilder: (context, i) {
  43. return _buildRow(snapshot.data[i]);
  44. },
  45. )
  46. : Center(
  47. child: CircularProgressIndicator(),
  48. );
  49. },
  50. )
  51. );
  52. }
  53. Widget _buildRow(Fruits fruit) {
  54. return new ListTile(
  55. title: new Text(fruit.name, style: _biggerFont),
  56. );
  57. }
  58. }
The application can be run to show the following output:
How To Create Listview in Flutter Dynamic
For the complete source code, click here.
Thank you for reading this article about how to create a listview in Flutter Dynamic. I hope this article is useful to you. Visit My Github about Flutter Here.