DRY up some search and places code

This commit is contained in:
Joshua Burman 2025-01-05 00:45:27 -05:00
parent 95701c73a6
commit ecc9aa3abc
4 changed files with 72 additions and 57 deletions

View File

@ -0,0 +1,12 @@
class GooglePlaceModel {
final String placeId;
final String description;
final String address;
final List<dynamic>? imageReferences;
GooglePlaceModel(
{required this.placeId,
required this.description,
required this.address,
this.imageReferences});
}

View File

@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart'; import 'package:http/http.dart';
import 'package:sendtrain/models/google_place_model.dart';
import 'package:sendtrain/widgets/generic/elements/form_search_input.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
class GooglePlacesService { class GooglePlacesService {
@ -33,11 +35,12 @@ class GooglePlacesService {
if (result.isNotEmpty) { if (result.isNotEmpty) {
return result['places'] return result['places']
.map<Suggestion>((p) => Suggestion( .map<Suggestion>((p) => Suggestion<GooglePlaceModel>(
placeId: p['id'], GooglePlaceModel(
description: p['displayName']['text'], placeId: p['id'],
address: p['formattedAddress'], description: p['displayName']['text'],
imageReferences: p['photos'])) address: p['formattedAddress'],
imageReferences: p['photos'])))
.toList(); .toList();
} else { } else {
return null; return null;
@ -52,9 +55,10 @@ class GooglePlacesService {
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
}; };
var request = Request('GET', var request = Request(
Uri.parse('https://places.googleapis.com/v1/$name/media?key=$apiKey&maxWidthPx=800&skipHttpRedirect=true') 'GET',
); Uri.parse(
'https://places.googleapis.com/v1/$name/media?key=$apiKey&maxWidthPx=800&skipHttpRedirect=true'));
request.headers.addAll(headers); request.headers.addAll(headers);
StreamedResponse response = await request.send(); StreamedResponse response = await request.send();
@ -72,28 +76,3 @@ class GooglePlacesService {
} }
} }
} }
class Suggestion {
final String placeId;
final String description;
final String address;
final List<dynamic>? imageReferences;
Suggestion(
{required this.placeId,
required this.description,
required this.address,
this.imageReferences});
@override
String toString() {
return 'Suggestion(description: $description, placeId: $placeId)';
}
Map toJson() => {
'placeId': placeId,
'name': description,
'address': address,
'imageReferences': imageReferences
};
}

View File

@ -2,17 +2,28 @@ import 'dart:async';
import 'dart:math'; import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:sendtrain/services/apis/google_places_service.dart';
import 'package:sendtrain/services/functional/debouncer.dart'; import 'package:sendtrain/services/functional/debouncer.dart';
import 'package:sendtrain/widgets/generic/elements/form_text_input.dart'; import 'package:sendtrain/widgets/generic/elements/form_text_input.dart';
class Suggestion<T> {
T type;
Suggestion(this.type);
}
class FormSearchInput extends StatefulWidget { class FormSearchInput extends StatefulWidget {
const FormSearchInput( const FormSearchInput(
{super.key, required this.sessionController, required this.service, this.requestCallback, this.optionalPayload}); {super.key,
required this.sessionController,
required this.service,
this.title,
this.callback,
this.optionalPayload});
final String? title;
final TextEditingController sessionController; final TextEditingController sessionController;
final dynamic service; final dynamic service;
final Function? requestCallback; final Function? callback;
final dynamic optionalPayload; final dynamic optionalPayload;
@override @override
@ -23,7 +34,7 @@ class _FormSearchInputState extends State<FormSearchInput> {
String? _currentQuery; String? _currentQuery;
late final service = widget.service; late final service = widget.service;
late final requestCallback = widget.requestCallback; late final callback = widget.callback;
// The most recent suggestions received from the API. // The most recent suggestions received from the API.
late Iterable<Widget> _lastOptions = <Widget>[]; late Iterable<Widget> _lastOptions = <Widget>[];
late final Debouncer debouncer; late final Debouncer debouncer;
@ -68,7 +79,7 @@ class _FormSearchInputState extends State<FormSearchInput> {
builder: (BuildContext context, SearchController controller) { builder: (BuildContext context, SearchController controller) {
return FormTextInput( return FormTextInput(
controller: widget.sessionController, controller: widget.sessionController,
title: 'Location (optional)', title: widget.title ?? "",
icon: Icon(Icons.search_rounded), icon: Icon(Icons.search_rounded),
maxLines: 2, maxLines: 2,
requiresValidation: false, requiresValidation: false,
@ -84,24 +95,15 @@ class _FormSearchInputState extends State<FormSearchInput> {
} }
_lastOptions = List<ListTile>.generate(options.length, (int index) { _lastOptions = List<ListTile>.generate(options.length, (int index) {
final Suggestion item = options[index]; final Suggestion item = options[index];
final dynamic content = item.type;
return ListTile( return ListTile(
title: Text(item.description), title: Text(content.description),
onTap: () async { onTap: () async {
// widget.optionalPayload = service.fetchPhoto(json.decode(item.image)); if (callback != null) {
if (item.imageReferences != null) { callback!(content, service);
// 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'];
});
} }
widget.optionalPayload.address = item.address; controller.closeView(null);
widget.sessionController.text = item.description;
service.finish();
controller.closeView(item.description);
}, },
); );
}); });

View File

@ -1,5 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:math';
import 'package:drift/drift.dart' hide Column; import 'package:drift/drift.dart' hide Column;
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
@ -181,9 +182,27 @@ class _SessionEditorState extends State<SessionEditor> {
}); });
}), }),
FormSearchInput( FormSearchInput(
title: 'Location (optional)',
sessionController: sessionCreateController['address']!, sessionController: sessionCreateController['address']!,
service: GooglePlacesService(), service: GooglePlacesService(),
optionalPayload: sessionPayload), callback: (content, service) async {
if (content.imageReferences != null) {
// get a random photo item from the returned result
Map<String, dynamic> photo = content.imageReferences![
Random().nextInt(content.imageReferences!.length)];
await service
.fetchPhoto(photo['name'])
.then((photoMap) {
sessionPayload.photoUri = photoMap['photoUri'];
});
}
sessionPayload.address = content.address;
sessionCreateController['address']!.text =
content.description;
service.finish();
}),
Padding( Padding(
padding: EdgeInsets.only(top: 10, bottom: 10), padding: EdgeInsets.only(top: 10, bottom: 10),
child: TextFormField( child: TextFormField(
@ -248,11 +267,15 @@ class _SessionEditorState extends State<SessionEditor> {
i++) { i++) {
PlatformFile file = PlatformFile file =
sessionPayload.files![i]; sessionPayload.files![i];
String? type = lookupMimeType(file.path!)!.split('/').first; String? type =
lookupMimeType(file.path!)!
.split('/')
.first;
Uint8List fileBytes = Uint8List fileBytes =
await file.xFile.readAsBytes(); await file.xFile.readAsBytes();
MediaType mediaType = MediaType.localImage; MediaType mediaType =
MediaType.localImage;
if (type == "video") { if (type == "video") {
mediaType = MediaType.localVideo; mediaType = MediaType.localVideo;
} }
@ -282,8 +305,7 @@ class _SessionEditorState extends State<SessionEditor> {
_formKey.currentContext!, 'Submit'); _formKey.currentContext!, 'Submit');
if (widget.callback != null) { if (widget.callback != null) {
await widget await widget.callback!();
.callback!();
} }
}) })
} }