On this page16 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. The Screen Skeleton
  5. 2. How ValueListenableBuilder Works
  6. 3. Empty State
  7. 4. Tapping and Deleting
  8. 5. The Missing Screen
  9. Code Examples
  10. Common Beginner Mistakes
  11. Best Practices
  12. Mini Challenge
  13. Practice Questions
  14. Practice Answers
  15. Key Takeaways
  16. Full Code (Copy-Paste Reference)

Lecture 005: Dashboard: Show & Delete Records

Category3: Building the Screens
Lecture005 of 007
Estimated video length20 min
TargetFlutter 3.44 · Dart 3.12 · hive 2.2
LevelBeginner
VideoPart 2: UI Setup: Display, Add, Update & Manage Data
Source codeGitHub: urraan_hive_final_code

A list that updates by itself when the box changes: no setState, no manual refresh. ValueListenableBuilder listens to the box and rebuilds when a record is added, changed or deleted.

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lectures 001–004 and ListView.builder / ListTile (Essential Widgets 007).


Connection With Previous Lectures

The manager can save and delete, but nothing shows the data yet. The dashboard is the home screen: a list of all records, a + button, and a delete icon on every row.


Learning Objectives

  • Build the dashboard Scaffold with a FloatingActionButton
  • Use box.listenable() with ValueListenableBuilder
  • Show an empty-state message
  • Delete a record from a list row

1. The Screen Skeleton

dart
// lib/screen_dashboard.dart
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';

import 'data_hive/data_objects.dart';
import 'data_hive/general_box.dart';
import 'screen_add_update_record.dart';

class ScreenDashboard extends StatelessWidget {
  const ScreenDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dashboard')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (_) => const ScreenAddUpdateRecord()),
          );
        },
        child: const Icon(Icons.add),
      ),
      body: ValueListenableBuilder(
        valueListenable: GeneralBox.getBox().listenable(),
        builder: (context, Box<DataObjects> box, _) {
          if (box.values.isEmpty) {
            return const Center(child: Text('No data found'));
          }
          final values = box.values.toList();

          return ListView.builder(
            itemCount: values.length,
            itemBuilder: (context, index) {
              final item = values[index];
              return ListTile(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => ScreenAddUpdateRecord(item: item),
                    ),
                  );
                },
                title: Text(item.name),
                subtitle: Text(item.address),
                trailing: IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () => GeneralBox.delete(item.key),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

The screen is a StatelessWidget: the box holds the state, not the widget.

2. How ValueListenableBuilder Works

box.listenable() (from hive_flutter) is a ValueListenable: it notifies every time the box changes. ValueListenableBuilder rebuilds only its builder each time. Delete a row → the box changes → the list rebuilds. No setState.

3. Empty State

When box.values.isEmpty we show No data found instead of an empty white screen.

4. Tapping and Deleting

  • onTap opens the form with the record: update mode (Lecture 006).
  • The trailing icon calls GeneralBox.delete(item.key). That key is why we stored key in the model.

5. The Missing Screen

The file imports screen_add_update_record.dart. Create a placeholder so the app compiles:

dart
// lib/screen_add_update_record.dart (temporary)
import 'package:flutter/material.dart';
import 'data_hive/data_objects.dart';

class ScreenAddUpdateRecord extends StatelessWidget {
  final DataObjects? item;
  const ScreenAddUpdateRecord({super.key, this.item});

  @override
  Widget build(BuildContext context) =>
      const Scaffold(body: Center(child: Text('Form comes next')));
}

Code Examples

Example 1: Test the Delete Without a Form

Temporarily add two records in main after GeneralBox.init():

dart
if (GeneralBox.getBox().isEmpty) {
  for (final name in ['Ali', 'Sara']) {
    GeneralBox.addUpdate(
      DataObjects()
        ..key = GeneralBox.getUniqueKey() + name
        ..name = name
        ..address = 'Karachi',
    );
  }
}

Run, tap the delete icons, and restart: deleted rows stay gone. Remove the seed code afterwards.


Common Beginner Mistakes

1. Using setState after delete: unnecessary; the builder already rebuilds.

2. listenable() without importing hive_flutter: the method is an extension in that package; the plain hive import lacks it.

3. Forgetting the typed builder parameter: Box<DataObjects> box keeps box.values typed.


Best Practices

  • Keep the rebuilding region small: wrap only the list, not the whole Scaffold.
  • Always provide an empty state.
  • Use IconButton (bigger tap area) for the delete icon.

Mini Challenge

Show the number of records in the AppBar title: Dashboard (3). Where must the count be read so it updates automatically?


Practice Questions

  1. What does listenable() return? 2. Why no setState? 3. Where does the delete key come from? 4. What does the empty state prevent?

Practice Answers

  1. A ValueListenable<Box> that notifies when the box changes.
  2. ValueListenableBuilder rebuilds on every change.
  3. The key field stored in each record.
  4. A blank screen that looks broken.

(Challenge: put the AppBar inside the builder, or use a second ValueListenableBuilder.)


Key Takeaways

  • ValueListenableBuilder + box.listenable() = a live list.
  • Delete with the key saved in the record.
  • Show an empty-state message.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. The add/update form is still the Lecture 005 placeholder: Lecture 006 replaces it with the real screen.

lib/data_hive/data_objects.dart: the model

dart
import 'dart:typed_data';

import 'package:hive/hive.dart';

part 'data_objects.g.dart';

@HiveType(typeId: 0)
class DataObjects {
  @HiveField(0)
  dynamic key; // stored on itself so the dashboard can delete/update by this value

  @HiveField(1, defaultValue: '')
  String name = '';

  @HiveField(2, defaultValue: '')
  String address = '';

  @HiveField(3)
  Uint8List? profileImage; // not used until Lecture 007

  @HiveField(4, defaultValue: [])
  List<String> hobbies = []; // not used until Lecture 007
}

lib/data_hive/data_objects.g.dart: generated adapter (reference only)

dart
// GENERATED CODE - DO NOT MODIFY BY HAND.
// Produced by: dart run build_runner build --delete-conflicting-outputs

part of 'data_objects.dart';

class DataObjectsAdapter extends TypeAdapter<DataObjects> {
  @override
  final int typeId = 0;

  @override
  DataObjects read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return DataObjects()
      ..key = fields[0]
      ..name = fields[1] as String
      ..address = fields[2] as String
      ..profileImage = fields[3] as Uint8List?
      ..hobbies = (fields[4] as List).cast<String>();
  }

  @override
  void write(BinaryWriter writer, DataObjects obj) {
    writer
      ..writeByte(5)
      ..writeByte(0)
      ..write(obj.key)
      ..writeByte(1)
      ..write(obj.name)
      ..writeByte(2)
      ..write(obj.address)
      ..writeByte(3)
      ..write(obj.profileImage)
      ..writeByte(4)
      ..write(obj.hobbies);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is DataObjectsAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

lib/data_hive/general_box.dart: the manager

dart
import 'package:hive_flutter/hive_flutter.dart';

import 'data_objects.dart';

class GeneralBox {
  static const String dataObjects = 'DataObjects';

  static Future<void> init() async {
    await Hive.initFlutter();
    if (!Hive.isAdapterRegistered(DataObjectsAdapter().typeId)) {
      Hive.registerAdapter(DataObjectsAdapter());
    }
    if (!Hive.isBoxOpen(dataObjects)) {
      await Hive.openBox<DataObjects>(dataObjects);
    }
  }

  static Box<DataObjects> getBox() => Hive.box<DataObjects>(dataObjects);

  static String getUniqueKey() =>
      DateTime.now().millisecondsSinceEpoch.toString();

  static bool addUpdate(DataObjects item) {
    final box = getBox();
    box.put(item.key, item);
    return box.containsKey(item.key);
  }

  static bool delete(String key) {
    final box = getBox();
    box.delete(key);
    return !box.containsKey(key);
  }

  static List<DataObjects> getAll() => getBox().values.toList();
}

lib/screen_dashboard.dart: the live list

dart
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';

import 'data_hive/data_objects.dart';
import 'data_hive/general_box.dart';
import 'screen_add_update_record.dart';

class ScreenDashboard extends StatelessWidget {
  const ScreenDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dashboard')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // No `item:` passed → the form opens in add mode.
          Navigator.push(
            context,
            MaterialPageRoute(builder: (_) => const ScreenAddUpdateRecord()),
          );
        },
        child: const Icon(Icons.add),
      ),
      // listenable() + ValueListenableBuilder keep this list in sync with the box - 
      // no setState anywhere on this screen.
      body: ValueListenableBuilder(
        valueListenable: GeneralBox.getBox().listenable(),
        builder: (context, Box<DataObjects> box, _) {
          if (box.values.isEmpty) {
            return const Center(child: Text('No data found'));
          }
          final values = box.values.toList();

          return ListView.builder(
            itemCount: values.length,
            itemBuilder: (context, index) {
              final item = values[index];
              return ListTile(
                onTap: () {
                  // Passing `item:` switches the form into update mode.
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => ScreenAddUpdateRecord(item: item),
                    ),
                  );
                },
                title: Text(item.name),
                subtitle: Text(item.address),
                trailing: IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () => GeneralBox.delete(item.key),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

lib/screen_add_update_record.dart: temporary placeholder

dart
// Just enough to let the app compile; Lecture 006 replaces this with the real form.
import 'package:flutter/material.dart';
import 'data_hive/data_objects.dart';

class ScreenAddUpdateRecord extends StatelessWidget {
  final DataObjects? item;
  const ScreenAddUpdateRecord({super.key, this.item});

  @override
  Widget build(BuildContext context) =>
      const Scaffold(body: Center(child: Text('Form comes next')));
}

lib/main.dart

dart
import 'package:flutter/material.dart';

import 'data_hive/general_box.dart';
import 'screen_dashboard.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await GeneralBox.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(colorSchemeSeed: Colors.deepPurple),
      home: const ScreenDashboard(),
    );
  }
}

Video lecture

Lecture 005 · 20 min