comigor / fuzzy

Fuzzy search in Dart
MIT License
37 stars 20 forks source link

Doesn't work with data models #9

Closed lukepighetti closed 4 years ago

lukepighetti commented 4 years ago

fuzzy works great with List<String> but if we provide data models with a toString() method it does not return any results. Screenshot and reproduction below.

ezgif-4-d957e2e4082d

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

class FuzzySearchRoute extends StatefulWidget {
  @override
  _FuzzySearchRouteState createState() => _FuzzySearchRouteState();
}

class _FuzzySearchRouteState extends State<FuzzySearchRoute> {
  String pattern = "";

  @override
  Widget build(BuildContext context) {
    final strings = ["foo", "bar", "baz", "biff"];
    final entries = [for (var e in strings) Entry(e)];

    final fuzzyString = Fuzzy(strings).search(pattern);
    final fuzzyEntry = Fuzzy(entries).search(pattern);

    return Scaffold(
      appBar: AppBar(
        title: Text("/fuzzy-search"),
      ),
      body: Align(
        alignment: Alignment.topCenter,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(height: 16),
            Text("Entries"),
            for (var e in entries) Text(e.value),

            /// String
            SizedBox(height: 16),
            Text("Results (String)"),
            for (var e in fuzzyString) Text(e.item),

            /// Entry
            SizedBox(height: 16),
            Text("Results (Entry)"),
            for (var e in fuzzyEntry) Text(e.item.value),
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: CupertinoTextField(
            onChanged: (e) => setState(() => pattern = e),
          ),
        ),
      ),
    );
  }
}

class Entry {
  /// An example data model with searchable toString() method
  Entry(this.value);

  /// The underlying value to search
  final String value;

  /// Fuzzy searchable string
  @override
  String toString() => "$value";
}
lukepighetti commented 4 years ago

It wasn't clear to me that we had to setup a weighted key for data models.

    final options = FuzzyOptions(keys: [
      WeightedKey<Entry>(name: "toString", weight: 1.0, getter: (e) => e.toString()),
    ]);

Would be nice to have it work with toString() out of the box. Feel free to close this issue.