How To Create Listview In Flutter Dynamic

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.  
  4. # The following defines the version and build number for your application.  
  5. # A version number is three numbers separated by dots, like 1.2.43  
  6. # followed by an optional build number separated by a +.  
  7. # Both the version and the builder number may be overridden in flutter  
  8. # build by specifying --build-name and --build-number, respectively.  
  9. # In Android, build-name is used as versionName while build-number used as versionCode.  
  10. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning  
  11. # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.  
  12. # Read more about iOS versioning at  
  13. # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html  
  14. version: 1.0.0+1  
  15.   
  16. environment:  
  17.   sdk: ">=2.1.0 <3.0.0"  
  18.   
  19. dependencies:  
  20.   flutter:  
  21.     sdk: flutter  
  22.  
  23.   # The following adds the Cupertino Icons font to your application.  
  24.   # Use with the CupertinoIcons class for iOS style icons.  
  25.   cupertino_icons: ^0.1.2  
  26.   english_words: ^3.1.0  
  27.   sqflite: any  
  28.   path_provider: ^0.4.0  
  29.     
  30. dev_dependencies:  
  31.   flutter_test:  
  32.     sdk: flutter  
  33.  
  34.  
  35. # For information on the generic Dart part of this file, see the  
  36. # following page: https://www.dartlang.org/tools/pub/pubspec  
  37.  
  38. # The following section is specific to Flutter.  
  39. flutter:  
  40.  
  41.   # The following line ensures that the Material Icons font is  
  42.   # included with your application, so that you can use the icons in  
  43.   # the material Icons class.  
  44.   uses-material-design: true    
  45.   assets:  
  46.    - data/flutter.db  
  47.   # To add assets to your application, add an assets section, like this:  
  48.   # assets:  
  49.   #  - images/a_dot_burr.jpeg  
  50.   #  - images/a_dot_ham.jpeg  
  51.  
  52.   # An image asset can refer to one or more resolution-specific "variants", see  
  53.   # https://flutter.dev/assets-and-images/#resolution-aware.  
  54.  
  55.   # For details regarding adding assets from package dependencies, see  
  56.   # https://flutter.dev/assets-and-images/#from-packages  
  57.  
  58.   # To add custom fonts to your application, add a fonts section here,  
  59.   # in this "flutter" section. Each entry in this list should have a  
  60.   # "family" key with the font family name, and a "fonts" key with a  
  61.   # list giving the asset and other descriptors for the font. For  
  62.   # example:  
  63.   # fonts:  
  64.   #   - family: Schyler  
  65.   #     fonts:  
  66.   #       - asset: fonts/Schyler-Regular.ttf  
  67.   #       - asset: fonts/Schyler-Italic.ttf  
  68.   #         style: italic  
  69.   #   - family: Trajan Pro  
  70.   #     fonts:  
  71.   #       - asset: fonts/TrajanPro.ttf  
  72.   #       - asset: fonts/TrajanPro_Bold.ttf  
  73.   #         weight: 700  
  74.   #  
  75.   # For details regarding fonts from package dependencies,  
  76.   # 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.   
  5.   Fruits(this._name);  
  6.   
  7.   Fruits.fromMap(dynamic obj) {  
  8.     this._name = obj['name'];  
  9.   }  
  10.   
  11.   String get name => _name;  
  12.   
  13.   Map<String, dynamic> toMap() {  
  14.     var map = new Map<String, dynamic>();  
  15.     map["name"] = _name;  
  16.     return map;  
  17.   }  

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.   
  10. class DatabaseHelper {  
  11.   static final DatabaseHelper _instance = new DatabaseHelper.internal();  
  12.   factory DatabaseHelper() => _instance;  
  13.   
  14.   static Database _db;  
  15.   
  16.   Future<Database> get db async {  
  17.     if (_db != null) {  
  18.       return _db;  
  19.     }  
  20.     _db = await initDb();  
  21.     return _db;  
  22.   }  
  23.   
  24.   DatabaseHelper.internal();  
  25.   
  26.   initDb() async {  
  27.     Directory documentDirectory = await getApplicationDocumentsDirectory();  
  28.     String path = join(documentDirectory.path, "data_flutter.db");  
  29.       
  30.     // Only copy if the database doesn't exist  
  31.     //if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound){  
  32.       // Load database from asset and copy  
  33.       ByteData data = await rootBundle.load(join('data''flutter.db'));  
  34.       List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);  
  35.   
  36.       // Save copied asset to documents  
  37.       await new File(path).writeAsBytes(bytes);  
  38.     //}  
  39.   
  40.     var ourDb = await openDatabase(path);  
  41.     return ourDb;  
  42.   }  

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.   
  5. class QueryCtr {  
  6. DatabaseHelper con = new DatabaseHelper();  
  7.   
  8.   Future<List<Fruits>> getAllFruits() async {  
  9.     var dbClient = await con.db;  
  10.     var res = await dbClient.query("fruits");  
  11.       
  12.     List<Fruits> list =  
  13.         res.isNotEmpty ? res.map((c) => Fruits.fromMap(c)).toList() : null;  
  14.   
  15.     return list;  
  16.   }  

Later, we create main.dart
  1. import 'package:flutter/material.dart';  
  2. import 'package:recyclerview/fruit.dart';  
  3. import 'package:recyclerview/query.dart';  
  4.   
  5. void main() => runApp(new MyApp());  
  6.   
  7. class MyApp extends StatelessWidget {  
  8.   @override  
  9.   Widget build(BuildContext context) {  
  10.     return new MaterialApp(  
  11.       title: "List in Flutter",  
  12.       home: new Scaffold(  
  13.         appBar: new AppBar(  
  14.           title: Text("List"),  
  15.         ),  
  16.         body: RandomFruits(),  
  17.       ),  
  18.     );  
  19.   }  
  20. }  
  21.   
  22. class RandomFruits extends StatefulWidget {  
  23.   @override  
  24.   State<StatefulWidget> createState() {  
  25.     return new RandomFruitsState();  
  26.   }  
  27. }  
  28.   
  29. class RandomFruitsState extends State<RandomFruits>  {  
  30.   
  31.   final _biggerFont = const TextStyle(fontSize: 18.0);  
  32.   QueryCtr _query = new  QueryCtr();  
  33.   
  34.   @override  
  35.   Widget build(BuildContext context) {  
  36.     return Scaffold (  
  37.       appBar: AppBar(  
  38.         title: Text('Load data from DB'),  
  39.       ),  
  40.       body: FutureBuilder<List>(  
  41.         future: _query.getAllFruits(),  
  42.         initialData: List(),  
  43.         builder: (context, snapshot) {  
  44.             return snapshot.hasData ?  
  45.              new ListView.builder(  
  46.               padding: const EdgeInsets.all(10.0),  
  47.               itemCount: snapshot.data.length,  
  48.               itemBuilder: (context, i) {  
  49.                 return _buildRow(snapshot.data[i]);  
  50.               },  
  51.             )  
  52.             : Center(  
  53.                           child: CircularProgressIndicator(),  
  54.                         );  
  55.         },  
  56.       )  
  57.     );  
  58.   }  
  59.   
  60.   Widget _buildRow(Fruits fruit) {  
  61.     return new ListTile(  
  62.       title: new Text(fruit.name, style: _biggerFont),  
  63.     );  
  64.   }  

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.


Similar Articles