Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AutoComplete control #3003

Merged
merged 3 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions packages/flet/lib/src/controls/auto_complete.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'dart:convert';

import 'package:flutter/material.dart';

import '../flet_control_backend.dart';
import '../models/control.dart';
import '../utils/auto_complete.dart';
import 'create_control.dart';

class AutoCompleteControl extends StatelessWidget {
final Control? parent;
final Control control;
final FletControlBackend backend;

const AutoCompleteControl(
{super.key,
required this.parent,
required this.control,
required this.backend});

@override
Widget build(BuildContext context) {
debugPrint("AutoComplete build: ${control.id}");

var suggestionsMaxHeight = control.attrDouble("suggestionsMaxHeight", 200)!;
var suggestions = parseAutoCompleteSuggestions(control, "suggestions");

var auto = Autocomplete(
optionsMaxHeight: suggestionsMaxHeight,
onSelected: (AutoCompleteSuggestion selection) {
backend.triggerControlEvent(
control.id,
"select",
//suggestions.indexOf(selection).toString()
json.encode(AutoCompleteSuggestion(
key: selection.key, value: selection.value)
.toJson()));
},
// optionsViewBuilder: optionsViewBuilder,
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') {
return const Iterable<AutoCompleteSuggestion>.empty();
}
return suggestions.where((AutoCompleteSuggestion suggestion) {
return suggestion
.selectionString()
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
);

return baseControl(context, auto, parent, control);
}
}
9 changes: 8 additions & 1 deletion packages/flet/lib/src/controls/create_control.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'dart:math';

import 'package:collection/collection.dart';
import 'package:flet/src/controls/semantics_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';

Expand All @@ -17,6 +16,7 @@ import '../utils/theme.dart';
import '../utils/transforms.dart';
import 'alert_dialog.dart';
import 'animated_switcher.dart';
import 'auto_complete.dart';
import 'badge.dart';
import 'banner.dart';
import 'barchart.dart';
Expand Down Expand Up @@ -96,6 +96,7 @@ import 'search_anchor.dart';
import 'segmented_button.dart';
import 'selection_area.dart';
import 'semantics.dart';
import 'semantics_service.dart';
import 'shader_mask.dart';
import 'shake_detector.dart';
import 'slider.dart';
Expand Down Expand Up @@ -701,6 +702,12 @@ Widget createWidget(
parentDisabled: parentDisabled,
parentAdaptive: parentAdaptive,
backend: backend);
case "autocomplete":
return AutoCompleteControl(
key: key,
parent: parent,
control: controlView.control,
backend: backend);
case "textfield":
return TextFieldControl(
key: key,
Expand Down
16 changes: 16 additions & 0 deletions packages/flet/lib/src/models/control.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:convert';

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

Expand Down Expand Up @@ -115,6 +117,20 @@ class Control extends Equatable {
defValue;
}

List? attrList(String name, [List? defValue = const []]) {
var l = attrString(name);
if (l == null) {
return defValue;
} else {
try {
return jsonDecode(l) as List;
} catch (e) {
debugPrint("attrList error while parsing $name: $e");
return defValue;
}
}
}

Control copyWith(
{String? id,
String? pid,
Expand Down
85 changes: 85 additions & 0 deletions packages/flet/lib/src/utils/auto_complete.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import 'dart:convert';

import 'package:flutter/material.dart';

import '../models/control.dart';

@immutable
class AutoCompleteSuggestion {
const AutoCompleteSuggestion({
required this.key,
required this.value,
});

final String key;
final String value;

@override
String toString() {
return value;
}

String selectionString() {
return key;
}

Map<String, dynamic> toJson() => <String, dynamic>{
'key': key,
'value': value,
};

@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is AutoCompleteSuggestion &&
other.key == key &&
other.value == value;
}

@override
int get hashCode => Object.hash(key, value);
}

List<AutoCompleteSuggestion> parseAutoCompleteSuggestions(
Control control, String propName) {
var v = control.attrString(propName, null);
if (v == null) {
return [];
}

final j1 = json.decode(v);
return autoCompleteSuggestionsFromJSON(j1);
}

List<AutoCompleteSuggestion> autoCompleteSuggestionsFromJSON(dynamic json) {
List<AutoCompleteSuggestion> m = [];
if (json is List) {
json.map((e) => autoCompleteSuggestionFromJSON(e)).toList().forEach((e) {
if (e != null) {
m.add(e);
}
});
}
return m;
}

AutoCompleteSuggestion? autoCompleteSuggestionFromJSON(dynamic json) {
var key = json["key"];
var value = json["value"];
if ((key == null || key.toString().isEmpty) &&
(value == null || value.toString().isEmpty)) {
return null;
}
if (key == null && value != null) {
key = value;
}
if (value == null && key != null) {
value = key;
}
return AutoCompleteSuggestion(
key: key.toString(),
value: value.toString(),
);
}
1 change: 1 addition & 0 deletions sdk/python/packages/flet-core/src/flet_core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from flet_core.app_bar import AppBar
from flet_core.audio import Audio
from flet_core.audio_recorder import AudioEncoder, AudioRecorder
from flet_core.auto_complete import AutoComplete, AutoCompleteSuggestion
from flet_core.badge import Badge
from flet_core.banner import Banner
from flet_core.blur import Blur, BlurTileMode
Expand Down
100 changes: 100 additions & 0 deletions sdk/python/packages/flet-core/src/flet_core/auto_complete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import dataclasses
import json
from typing import Any, Optional, List

from flet_core.control import Control, OptionalNumber
from flet_core.control_event import ControlEvent
from flet_core.event_handler import EventHandler
from flet_core.ref import Ref


@dataclasses.dataclass
class AutoCompleteSuggestion:
key: str = dataclasses.field(default=None)
value: str = dataclasses.field(default=None)


class AutoComplete(Control):
"""
Helps the user make a selection by entering some text and choosing from among a list of displayed options.

-----

Online docs: https://flet.dev/docs/controls/autocomplete
"""

def __init__(
self,
suggestions: Optional[List[AutoCompleteSuggestion]] = None,
suggestions_max_height: OptionalNumber = None,
on_select=None,
#
# Control
#
ref: Optional[Ref] = None,
opacity: OptionalNumber = None,
visible: Optional[bool] = None,
data: Any = None,
):

Control.__init__(
self,
ref=ref,
opacity=opacity,
visible=visible,
data=data,
)

def convert_event_data(e):
print(e.data)
d = json.loads(e.data)
return AutoCompleteSelectEvent(**d)

self.__on_select = EventHandler(convert_event_data)
self._add_event_handler("select", self.__on_select.get_handler())

self.suggestions = suggestions
self.suggestions_max_height = suggestions_max_height
self.on_select = on_select

def _get_control_name(self):
return "autocomplete"

def before_update(self):
self._set_attr_json("suggestions", self.__suggestions)

# suggestions_max_height
@property
def suggestions_max_height(self) -> OptionalNumber:
return self._get_attr(
"suggestionsMaxHeight", data_type="float", def_value=200.0
)

@suggestions_max_height.setter
def suggestions_max_height(self, value: OptionalNumber):
self._set_attr("suggestionsMaxHeight", value)

# suggestions
@property
def suggestions(self) -> Optional[List[AutoCompleteSuggestion]]:
return self.__suggestions

@suggestions.setter
def suggestions(self, value: Optional[List[str]]):
self.__suggestions = value or []

# on_select
@property
def on_select(self):
return self._get_event_handler("select")

@on_select.setter
def on_select(self, handler):
self.__on_select.subscribe(handler)


class AutoCompleteSelectEvent(ControlEvent):
def __init__(self, key: str, value: str) -> None:
self.selection: AutoCompleteSuggestion = AutoCompleteSuggestion(
key=key, value=value
)
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def selected_index(self) -> Optional[int]:

@selected_index.setter
def selected_index(self, value: Optional[int]):
if value is not None and (0 <= value <= len(self.controls) - 1):
if value is not None and not (0 <= value < len(self.controls)):
raise IndexError("selected_index out of range")
self._set_attr("selectedIndex", value)

Expand Down