Select all products from the database
Now it's time to get all the stored product in the database, let's select and fetch the data using sqflite and list them in the home page.
First thing as always is to import the neccessery files.
import '../models/product.dart';
import '../services/dbhelper.dart';
Next thing to do is to instantiate the database.
DbHelper helper;
@override
void initState() {
super.initState();
helper = DbHelper();
}
Since we are working asynchronously and waiting for data to be fetched, we are going to use FutureBuilder
widget.
So here is the final code for the home page.
import 'package:flutter/material.dart';
import './update_product_page.dart';
import './view_product_page.dart';
import './add_product_page.dart';
import '../models/product.dart';
import '../services/dbhelper.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
DbHelper helper;
@override
void initState() {
super.initState();
helper = DbHelper();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: FutureBuilder(
future: helper.getProducts(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
Product product = Product.fromMap(snapshot.data[index]);
return ListTile(
contentPadding: const EdgeInsets.all(16),
title:
Text("${product.name} - \$${(product.price).toString()}"),
subtitle: Text(product.description),
trailing: Column(
children: [
Expanded(
child: IconButton(
icon: Icon(
Icons.delete,
color: Colors.red,
),
onPressed: () {}),
),
SizedBox(height: 20),
Expanded(
child: IconButton(
icon: Icon(
Icons.edit,
color: Colors.blue,
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => UpdateProductPage(),
),
);
},
),
),
],
),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ProductDetailsPage(),
),
);
},
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add, color: Colors.white),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AddProductPage(),
),
);
},
),
);
}
}