location image search and population for new session
This commit is contained in:
@ -1,34 +1,17 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart';
|
||||
import 'package:sendtrain/services/apis/google_places_service.dart';
|
||||
import 'package:sendtrain/services/functional/debouncer.dart';
|
||||
import 'package:sendtrain/widgets/generic/elements/form_text_input.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
class Suggestion {
|
||||
final String placeId;
|
||||
final String description;
|
||||
final String address;
|
||||
|
||||
Suggestion(this.placeId, this.description, this.address);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'Suggestion(description: $description, placeId: $placeId)';
|
||||
}
|
||||
|
||||
Map toJson() => {
|
||||
'placeId': placeId,
|
||||
'name': description,
|
||||
'address': address,
|
||||
};
|
||||
}
|
||||
|
||||
class FormSearchInput extends StatefulWidget {
|
||||
const FormSearchInput({super.key, required this.sessionController});
|
||||
const FormSearchInput(
|
||||
{super.key, required this.sessionController, this.optionalPayload});
|
||||
|
||||
final TextEditingController sessionController;
|
||||
final dynamic optionalPayload;
|
||||
|
||||
@override
|
||||
State<FormSearchInput> createState() => _FormSearchInputState();
|
||||
@ -37,21 +20,22 @@ class FormSearchInput extends StatefulWidget {
|
||||
class _FormSearchInputState extends State<FormSearchInput> {
|
||||
String? _currentQuery;
|
||||
|
||||
final service = GooglePlacesService();
|
||||
|
||||
// The most recent suggestions received from the API.
|
||||
late Iterable<Widget> _lastOptions = <Widget>[];
|
||||
|
||||
late final _Debounceable<Iterable<String>?, String> _debouncedSearch;
|
||||
late final Debouncer debouncer;
|
||||
|
||||
// Calls the "remote" API to search with the given query. Returns null when
|
||||
// the call has been made obsolete.
|
||||
Future<Iterable<String>?> _search(String query) async {
|
||||
Future<Iterable<Suggestion>?> _search(String query) async {
|
||||
_currentQuery = query;
|
||||
|
||||
// In a real application, there should be some error handling here.
|
||||
// final Iterable<String> options = await _FakeAPI.search(_currentQuery!);
|
||||
if (query.isNotEmpty) {
|
||||
final List<Suggestion>? suggestions =
|
||||
await fetchSuggestions(_currentQuery!, 'en');
|
||||
await service.fetchSuggestions(_currentQuery!, 'en');
|
||||
|
||||
// If another search happened after this one, throw away these options.
|
||||
if (_currentQuery != query) {
|
||||
@ -59,50 +43,16 @@ class _FormSearchInputState extends State<FormSearchInput> {
|
||||
}
|
||||
_currentQuery = null;
|
||||
|
||||
return suggestions?.map((suggestion) => json.encode(suggestion));
|
||||
return suggestions?.map((suggestion) => suggestion);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
final sessionToken = Uuid().v4();
|
||||
final apiKey = "AIzaSyBCjMCEAyyNVpsnVYvZj6VL1mmB98Vd6AE";
|
||||
final client = Client();
|
||||
|
||||
Future<List<Suggestion>?> fetchSuggestions(String input, String lang) async {
|
||||
var headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Goog-Api-Key': apiKey,
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
'X-Goog-FieldMask': 'places.displayName,places.id,places.formattedAddress'
|
||||
};
|
||||
var request = Request('POST',
|
||||
Uri.parse('https://places.googleapis.com/v1/places:searchText'));
|
||||
request.body = json.encode({"textQuery": input});
|
||||
request.headers.addAll(headers);
|
||||
|
||||
StreamedResponse response = await request.send();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final result = json.decode(await response.stream.bytesToString());
|
||||
|
||||
if (result.isNotEmpty) {
|
||||
return result['places']
|
||||
.map<Suggestion>((p) => Suggestion(
|
||||
p['id'], p['displayName']['text'], p['formattedAddress']))
|
||||
.toList();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
throw Exception(response.reasonPhrase);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_debouncedSearch = _debounce<Iterable<String>?, String>(_search);
|
||||
debouncer = Debouncer(Duration(milliseconds: 50), _search);
|
||||
}
|
||||
|
||||
@override
|
||||
@ -114,28 +64,37 @@ class _FormSearchInputState extends State<FormSearchInput> {
|
||||
title: 'Location (optional)',
|
||||
icon: Icon(Icons.search_rounded),
|
||||
maxLines: 2,
|
||||
requiresValidation: false,
|
||||
onTap: () {
|
||||
controller.openView();
|
||||
});
|
||||
}, suggestionsBuilder:
|
||||
(BuildContext context, SearchController controller) async {
|
||||
final List<String>? options =
|
||||
(await _debouncedSearch(controller.text))?.toList();
|
||||
final List<Suggestion>? options =
|
||||
(await debouncer.process(controller.text))?.toList();
|
||||
if (options == null) {
|
||||
return _lastOptions;
|
||||
}
|
||||
_lastOptions = List<ListTile>.generate(options.length, (int index) {
|
||||
final String item = options[index];
|
||||
final Suggestion item = options[index];
|
||||
return ListTile(
|
||||
title: Text(json.decode(item)['name']),
|
||||
onTap: () {
|
||||
if (item.isNotEmpty) {
|
||||
widget.sessionController.text = json.decode(item)['name'];
|
||||
title: Text(item.description),
|
||||
onTap: () async {
|
||||
// widget.optionalPayload = service.fetchPhoto(json.decode(item.image));
|
||||
if (item.imageReferences != null) {
|
||||
// get a random photo item from the returned result
|
||||
Map<String, dynamic> photo = item.imageReferences![
|
||||
Random().nextInt(item.imageReferences!.length)];
|
||||
|
||||
await service.fetchPhoto(photo['name']).then((photoMap) {
|
||||
widget.optionalPayload.photoUri = photoMap['photoUri'];
|
||||
});
|
||||
}
|
||||
client.close();
|
||||
controller.closeView(item);
|
||||
// debugPrint('You just selected $item');
|
||||
// Navigator.of(context).pop();
|
||||
|
||||
widget.optionalPayload.address = item.address;
|
||||
widget.sessionController.text = item.description;
|
||||
service.finish();
|
||||
controller.closeView(item.description);
|
||||
},
|
||||
);
|
||||
});
|
||||
@ -144,55 +103,3 @@ class _FormSearchInputState extends State<FormSearchInput> {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const Duration debounceDuration = Duration(milliseconds: 500);
|
||||
typedef _Debounceable<S, T> = Future<S?> Function(T parameter);
|
||||
|
||||
/// Returns a new function that is a debounced version of the given function.
|
||||
///
|
||||
/// This means that the original function will be called only after no calls
|
||||
/// have been made for the given Duration.
|
||||
_Debounceable<S, T> _debounce<S, T>(_Debounceable<S?, T> function) {
|
||||
_DebounceTimer? debounceTimer;
|
||||
|
||||
return (T parameter) async {
|
||||
if (debounceTimer != null && !debounceTimer!.isCompleted) {
|
||||
debounceTimer!.cancel();
|
||||
}
|
||||
debounceTimer = _DebounceTimer();
|
||||
try {
|
||||
await debounceTimer!.future;
|
||||
} on _CancelException {
|
||||
return null;
|
||||
}
|
||||
return function(parameter);
|
||||
};
|
||||
}
|
||||
|
||||
// A wrapper around Timer used for debouncing.
|
||||
class _DebounceTimer {
|
||||
_DebounceTimer() {
|
||||
_timer = Timer(debounceDuration, _onComplete);
|
||||
}
|
||||
|
||||
late final Timer _timer;
|
||||
final Completer<void> _completer = Completer<void>();
|
||||
|
||||
void _onComplete() {
|
||||
_completer.complete();
|
||||
}
|
||||
|
||||
Future<void> get future => _completer.future;
|
||||
|
||||
bool get isCompleted => _completer.isCompleted;
|
||||
|
||||
void cancel() {
|
||||
_timer.cancel();
|
||||
_completer.completeError(const _CancelException());
|
||||
}
|
||||
}
|
||||
|
||||
// An exception indicating that the timer was canceled.
|
||||
class _CancelException implements Exception {
|
||||
const _CancelException();
|
||||
}
|
||||
|
@ -8,7 +8,8 @@ class FormTextInput extends StatelessWidget {
|
||||
this.icon,
|
||||
this.maxLines,
|
||||
this.minLines,
|
||||
this.onTap});
|
||||
this.onTap,
|
||||
this.requiresValidation=true});
|
||||
|
||||
final TextEditingController controller;
|
||||
final String title;
|
||||
@ -16,6 +17,7 @@ class FormTextInput extends StatelessWidget {
|
||||
final int? minLines;
|
||||
final Icon? icon;
|
||||
final dynamic onTap;
|
||||
final bool requiresValidation;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@ -34,12 +36,14 @@ class FormTextInput extends StatelessWidget {
|
||||
labelText: title,
|
||||
),
|
||||
validator: (String? value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Please enter some text';
|
||||
}
|
||||
if (requiresValidation == true) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Please enter some text';
|
||||
}
|
||||
|
||||
if (value.length < 3) {
|
||||
return 'Please enter a minimum of 3 characters';
|
||||
if (value.length < 3) {
|
||||
return 'Please enter a minimum of 3 characters';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
Reference in New Issue
Block a user