Search code examples
flutterdartindexingenumerateflutter-hive

How can I output my object properties with this enumerating extension in Flutter/Dart?


I want to print specific individualized object properties with this extension- Source: HERE

extension ExtendedIterable<E> on Iterable<E> {
  /// Like Iterable<T>.map but callback have index as second argument
  Iterable<T> mapIndex<T>(T f(E e, int i)) {
    var i = 0;
    return this.map((e) => f(e, i++));
  }

  void forEachIndex(void f(E e, int i)) {
    var i = 0;
    this.forEach((e) => f(e, i++));
  }
}

I am saving user data from textFields into a Hive box.

When I do the following...

final box = Hive.box(personTable).values.toList();
    final hiveBox = Hive.box(personTable);
    final indexingBox = box.mapIndex((e, i) => 'item$e index$i');
    final Person person = hiveBox.getAt(0);
    print(person);
    print(indexingBox);

I get the following printed:

flutter: {John, Biggs, 34, Active}
flutter: (item{John, Biggs, 34, Active} index0, item{Kostas, Panger, 76, Active} index1, item{Ben, Kenobi, 78, Deactivated} index2, ..., item{Luke, Skywalker, 45, Active} index5, item{Darth, Vader, 54, Active} index6)

I want to be able to enumerate selectively, each object property as I please.

This is what I want to be able to print:

  • flutter: John. // index 0 firstName
  • flutter: Kostas // index 1 firstName
  • flutter: Vader // index 6 lastname

Class saving into Hive box:

import 'package:hive/hive.dart';
part 'person.g.dart';

@HiveType(typeId: 0)
class Person {
  @HiveField(0)
  final String firstName;
  @HiveField(1)
  final String lastName;
  @HiveField(2)
  final String age;
  @HiveField(3)
  final String status;
  Income({
    this.firstName,
    this.lastName,
    this.age,
    this.status,
  });
  @override
  String toString() {
    return '{${this.firstName}, ${this.lastName}, ${this.age}, ${this.status}}';
  }
}

If I can't solve this once and for all my head may as well explode, this is part of a bigger picture of making a DataTable very simple and dynamically loading. Help is appreciated!


Solution

  • SOLVED, FINALLY!!!

    box.forEachIndex((e, i) {
          final hiveBox = Hive.box(personTable);
          final person = hiveBox.getAt(i) as Person;
          print('${person.firstName}');
        });
    

    Console

    flutter: John
    flutter: Obi-wan
    flutter: Luke