On this page15 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. One Screen, Two Modes
  5. 2. Fill the Form for Update
  6. 3. Save
  7. 4. The Full Screen (Name and Address)
  8. Code Examples
  9. Common Beginner Mistakes
  10. Best Practices
  11. Mini Challenge
  12. Practice Questions
  13. Practice Answers
  14. Key Takeaways
  15. Full Code (Copy-Paste Reference)

Lecture 006: Add & Update Records

Category3: Building the Screens
Lecture006 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

One form, two jobs. Opened from the + button it adds a record; opened by tapping a row it updates that record. The only difference is whether it receives an existing item.

Contents

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


Prerequisites

Lectures 001–005; TextField and TextEditingController (Essential Widgets).


Connection With Previous Lectures

The dashboard opens ScreenAddUpdateRecord() for add and ScreenAddUpdateRecord(item: item) for update. Now we build that screen.


Learning Objectives

  • Make one screen that works in add and update mode
  • Fill the fields from an existing record in initState
  • Save with GeneralBox.addUpdate, reusing the key when updating
  • Dispose controllers

1. One Screen, Two Modes

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

  @override
  State<ScreenAddUpdateRecord> createState() => _ScreenAddUpdateRecordState();
}

item == null → add. item != null → update. A getter keeps the checks readable:

dart
bool get _isUpdate => widget.item != null;

2. Fill the Form for Update

dart
final controllerName = TextEditingController();
final controllerAddress = TextEditingController();

@override
void initState() {
  super.initState();
  final item = widget.item;
  if (item != null) {
    controllerName.text = item.name;
    controllerAddress.text = item.address;
  }
}

@override
void dispose() {
  controllerName.dispose();
  controllerAddress.dispose();
  super.dispose();
}

initState runs once, before the first build: the right place to copy values into the controllers. dispose frees them.

3. Save

dart
void _save() {
  final item = DataObjects()
    ..key = widget.item?.key ?? GeneralBox.getUniqueKey()
    ..name = controllerName.text.trim()
    ..address = controllerAddress.text.trim();

  if (GeneralBox.addUpdate(item)) {
    Navigator.pop(context);
  }
}

The one important line is widget.item?.key ?? GeneralBox.getUniqueKey(): reuse the old key when updating, create a new key when adding. Same key → put replaces the record. New key → put adds one.

Navigator.pop returns to the dashboard, which has already refreshed itself.

4. The Full Screen (Name and Address)

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

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

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

  @override
  State<ScreenAddUpdateRecord> createState() => _ScreenAddUpdateRecordState();
}

class _ScreenAddUpdateRecordState extends State<ScreenAddUpdateRecord> {
  final controllerName = TextEditingController();
  final controllerAddress = TextEditingController();

  bool get _isUpdate => widget.item != null;

  @override
  void initState() {
    super.initState();
    final item = widget.item;
    if (item != null) {
      controllerName.text = item.name;
      controllerAddress.text = item.address;
    }
  }

  @override
  void dispose() {
    controllerName.dispose();
    controllerAddress.dispose();
    super.dispose();
  }

  void _save() {
    final item = DataObjects()
      ..key = widget.item?.key ?? GeneralBox.getUniqueKey()
      ..name = controllerName.text.trim()
      ..address = controllerAddress.text.trim();

    if (GeneralBox.addUpdate(item)) {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(_isUpdate ? 'Update Record' : 'Add Record')),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          TextField(
            controller: controllerName,
            decoration: const InputDecoration(
              labelText: 'Name',
              hintText: 'Enter name',
            ),
          ),
          const SizedBox(height: 10),
          TextField(
            controller: controllerAddress,
            decoration: const InputDecoration(
              labelText: 'Address',
              hintText: 'Enter address',
            ),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _save,
            child: Text(_isUpdate ? 'Update Record' : 'Add Record'),
          ),
        ],
      ),
    );
  }
}

Run it: add two people, tap one, change the address, press Update Record, the list shows the new address. Close and reopen the app: everything is still there.


Code Examples

Example 1: Why the Key Matters

dart
// update: same key → one record, edited
item.key = widget.item!.key;

// bug: new key on update → a second record appears
item.key = GeneralBox.getUniqueKey();

Common Beginner Mistakes

1. Generating a new key on update: you get a duplicate instead of an edit.

2. Filling controllers in build: the text resets on every rebuild and the user cannot type. Use initState.

3. Forgetting dispose: controllers leak memory.

4. Using context after an await without checking mounted: in this screen _save is synchronous, so it is fine; in Lecture 007 the image picker is async and needs care.


Best Practices

  • trim() user text before saving.
  • Reject empty names (see the challenge).
  • Keep add and update in one screen; the form is identical.

Mini Challenge

Do not save when the name is empty: show a SnackBar saying Name is required and stay on the screen.


Practice Questions

  1. What decides add vs update? 2. Why reuse widget.item?.key? 3. Where do controllers get their starting text? 4. What does Navigator.pop do after saving?

Practice Answers

  1. Whether widget.item is null.
  2. put with the same key replaces the record.
  3. initState.
  4. Closes the form and returns to the dashboard.

Key Takeaways

  • One screen, item optional: null = add, not null = update.
  • Update = put with the same key.
  • Fill controllers in initState, dispose them in dispose.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. The form now replaces Lecture 005's placeholder; photo and hobbies are still not wired up until Lecture 007.

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;

  @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: () {
          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),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

lib/screen_add_update_record.dart: add & update form

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

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

class ScreenAddUpdateRecord extends StatefulWidget {
  // null → add mode; an existing record → update mode.
  final DataObjects? item;
  const ScreenAddUpdateRecord({super.key, this.item});

  @override
  State<ScreenAddUpdateRecord> createState() => _ScreenAddUpdateRecordState();
}

class _ScreenAddUpdateRecordState extends State<ScreenAddUpdateRecord> {
  final controllerName = TextEditingController();
  final controllerAddress = TextEditingController();

  bool get _isUpdate => widget.item != null;

  @override
  void initState() {
    super.initState();
    // Pre-fill the fields when editing an existing record. initState runs once,
    // before the first build, so this never fights with user typing.
    final item = widget.item;
    if (item != null) {
      controllerName.text = item.name;
      controllerAddress.text = item.address;
    }
  }

  @override
  void dispose() {
    // Always dispose controllers you created yourself, or they leak.
    controllerName.dispose();
    controllerAddress.dispose();
    super.dispose();
  }

  void _save() {
    final item = DataObjects()
      // The one line that decides add vs update: reuse the old key to replace
      // the existing record, or make a new key to create a new one.
      ..key = widget.item?.key ?? GeneralBox.getUniqueKey()
      ..name = controllerName.text.trim()
      ..address = controllerAddress.text.trim();

    if (GeneralBox.addUpdate(item)) {
      Navigator.pop(context); // back to the dashboard, which refreshes itself
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(_isUpdate ? 'Update Record' : 'Add Record')),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          TextField(
            controller: controllerName,
            decoration: const InputDecoration(
              labelText: 'Name',
              hintText: 'Enter name',
            ),
          ),
          const SizedBox(height: 10),
          TextField(
            controller: controllerAddress,
            decoration: const InputDecoration(
              labelText: 'Address',
              hintText: 'Enter address',
            ),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _save,
            child: Text(_isUpdate ? 'Update Record' : 'Add Record'),
          ),
        ],
      ),
    );
  }
}

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 006 · 20 min