Skip to content

Commit

Permalink
Modifiche alla serializzazione, modifiche alla posizione di vendita
Browse files Browse the repository at this point in the history
Took 29 minutes
  • Loading branch information
emiliodallatorre committed Nov 4, 2023
1 parent 9cfeea4 commit 2a58e8f
Show file tree
Hide file tree
Showing 11 changed files with 99 additions and 86 deletions.
3 changes: 2 additions & 1 deletion lib/interface/pages/book_search_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,11 @@ class BookSearchPage extends StatelessWidget {
markers: booksSnapshot.data
?.map((BookModel book) => book.results)
.expand((List<BookModel> bookResults) => bookResults)
.where((BookModel book) => book.modelizedLocation != null)
.map(
(BookModel book) => Marker(
markerId: MarkerId(book.id!),
position: LatLng(book.modelizedLocation.latitude, book.modelizedLocation.longitude),
position: LatLng(book.modelizedLocation!.latitude, book.modelizedLocation!.longitude),
icon: BitmapDescriptor.defaultMarkerWithHue(bookColors[book.secureIsbn]!.hue),
onTap: () async {
await Future.delayed(Duration(milliseconds: 256));
Expand Down
74 changes: 33 additions & 41 deletions lib/interface/screen/book_editor_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import 'package:bookaround/models/user_model.dart';
import 'package:bookaround/resources/helper/book_helper.dart';
import 'package:bookaround/resources/helper/geocoding_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_geocoder/geocoder.dart';
import 'package:flutter_geocoder/model.dart';
import 'package:geoflutterfire_plus/geoflutterfire_plus.dart';
import 'package:provider/provider.dart';

class BookEditorScreen extends StatefulWidget {
Expand Down Expand Up @@ -101,21 +102,29 @@ class _BookEditorScreenState extends State<BookEditorScreen> {
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
children: [
TextFormField(
key: locationKey,
// readOnly: true,
validator: (final String? value) {
if (value == null || value.isEmpty) return S.current.requiredField;
if (int.tryParse(value) == null || value.length != 5) return S.current.insertValidZipCode;

return null;
},
controller: locationController,
textInputAction: TextInputAction.search,
keyboardType: TextInputType.numberWithOptions(signed: true),
decoration: InputDecoration(
labelText: S.current.zipCodeOfBook,
suffixIcon: IconButton(
Row(
children: [
Expanded(
child: TextFormField(
key: locationKey,
// readOnly: true,
validator: (final String? value) {
if (!hasInsertedZipCode) {
if (value == null || value.isEmpty) return S.current.requiredField;
if (int.tryParse(value) == null || value.length != 5) return S.current.insertValidZipCode;
}

return null;
},
controller: locationController,
textInputAction: TextInputAction.search,
keyboardType: TextInputType.number,
readOnly: hasInsertedZipCode,
enabled: !hasInsertedZipCode,
decoration: InputDecoration(labelText: S.current.zipCodeOfBook),
),
),
IconButton(
icon: Icon(hasInsertedZipCode ? Icons.close : Icons.check),
onPressed: () async {
if (hasInsertedZipCode) {
Expand All @@ -128,42 +137,23 @@ class _BookEditorScreenState extends State<BookEditorScreen> {

setState(() {});
} else {
FocusScope.of(context).unfocus();

if (locationKey.currentState!.validate()) {
final (Address, Map<String, dynamic>) zipGeocoding = await GeocodingHelper.decodeZipCode(int.parse(locationController.text));
final (Address, GeoFirePoint) zipGeocoding = await GeocodingHelper.decodeZipCode(int.parse(locationController.text));
book.locationData = zipGeocoding.$2;
book.location = PlaceModel.fromAddress(zipGeocoding.$1);

debugPrint("Il libro si trova a ${book.location!.toJson().toString()}.");
// locationController.text = zipGeocoding.$1.adminArea;
locationController.text = book.location!.description!;
hasInsertedZipCode = true;

setState(() {});
}
}
},
),
),
/*onTap: () async {
Prediction? prediction = await PlacesAutocomplete.show(
context: context,
apiKey: References.googleApiKey,
mode: Mode.overlay,
language: Platform.localeName.split("_").first,
components: [
Component(Component.country, "it"),
Component(Component.country, "fr"),
],
);
if (prediction != null) {
debugPrint("Il libro si trova a ${prediction.description}.");
locationController.text = prediction.description!;
book!.location = PlaceModel.fromPrediction(prediction);
book!.locationData = await GeocodingHelper.decodeAddress(book!.location!.description!);
setState(() {});
}
},*/
],
),
TextFormField(
decoration: InputDecoration(labelText: S.current.note, alignLabelWithHint: true),
Expand All @@ -185,6 +175,8 @@ class _BookEditorScreenState extends State<BookEditorScreen> {
if (formKey.currentState!.validate()) {
formKey.currentState!.save();

debugPrint(book.toJson().toString());

await BookHelper.updateBook(book);
await sellBooksBloc.getUserBooks(Provider.of<UserModel>(context, listen: false).uid!, Provider.of<UserModel>(context, listen: false).blockedUids!);

Expand Down
48 changes: 27 additions & 21 deletions lib/interface/screen/book_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,23 @@ class BookScreen extends StatefulWidget {
}

class _BookScreenState extends State<BookScreen> {
BookModel? _book;
late BookModel book;

bool initialized = false;

@override
Widget build(BuildContext context) {
if (_book == null) _book = ModalRoute.of(context)!.settings.arguments as BookModel;
if (!initialized) {
book = ModalRoute.of(context)!.settings.arguments as BookModel;
initialized = true;
}

debugPrint(_book!.userUid);
debugPrint(book.userUid);

return Scaffold(
appBar: AppBar(
actions: [
if (_book!.userUid != Provider.of<UserModel>(context).uid)
if (book.userUid != Provider.of<UserModel>(context).uid)
PopupMenuButton(
itemBuilder: (BuildContext context) => <String>[S.current.reportBook]
.map((final String choice) => PopupMenuItem<String>(
Expand All @@ -49,7 +54,7 @@ class _BookScreenState extends State<BookScreen> {
.toList(),
onSelected: (final String choice) async {
if (choice == S.current.reportBook) {
ReportHelper.reportBook(_book!.id!, Provider.of<UserModel>(context, listen: false).uid!).whenComplete(() {
ReportHelper.reportBook(book.id!, Provider.of<UserModel>(context, listen: false).uid!).whenComplete(() {
if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(S.current.reportedBook)));
});
}
Expand All @@ -70,34 +75,34 @@ class _BookScreenState extends State<BookScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
BookCover(book: _book!, horizontalPadding: false),
BookCover(book: book, horizontalPadding: false),

Text(S.current.bookState, style: Theme.of(context).textTheme.headlineMedium),
Column(
children: [
Row(
children: [
Expanded(child: Text(S.current.pencil)),
Checkbox(value: _book!.pencil, onChanged: null),
Checkbox(value: book.pencil, onChanged: null),
],
),
Row(
children: [
Expanded(child: Text(S.current.pen)),
Checkbox(value: _book!.pen, onChanged: null),
Checkbox(value: book.pen, onChanged: null),
],
),
Row(
children: [
Expanded(child: Text(S.current.highlight)),
Checkbox(value: _book!.highlighting, onChanged: null),
Checkbox(value: book.highlighting, onChanged: null),
],
),
],
),
if (_book!.note!.isNotEmpty) Text(S.current.note, style: Theme.of(context).textTheme.bodySmall),
if (_book!.note!.isNotEmpty) Text(_book!.note!),
if (_book!.userUid != Provider.of<UserModel>(context).uid) _buildSellerInfo(context),
if (book.note!.isNotEmpty) Text(S.current.note, style: Theme.of(context).textTheme.bodySmall),
if (book.note!.isNotEmpty) Text(book.note!),
if (book.userUid != Provider.of<UserModel>(context).uid) _buildSellerInfo(context),
// _buildSellerInfo(context),
SizedBox(height: 16.0),
],
Expand All @@ -120,8 +125,8 @@ class _BookScreenState extends State<BookScreen> {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(_book!.user!.displayName, style: Theme.of(context).textTheme.titleLarge),
Text(_book!.user!.city!, style: Theme.of(context).textTheme.bodySmall),
Text(book.user!.displayName, style: Theme.of(context).textTheme.titleLarge),
Text(book.user!.city!, style: Theme.of(context).textTheme.bodySmall),
],
),
],
Expand All @@ -130,10 +135,10 @@ class _BookScreenState extends State<BookScreen> {
AspectRatio(
aspectRatio: 4 / 3,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: _book!.modelizedLocation, zoom: 12.0),
initialCameraPosition: CameraPosition(target: book.modelizedLocation!, zoom: 12.0),
myLocationEnabled: true,
myLocationButtonEnabled: false,
markers: <Marker>[Marker(markerId: MarkerId(_book!.id!), position: _book!.modelizedLocation)].toSet(),
markers: <Marker>[Marker(markerId: MarkerId(book.id!), position: book.modelizedLocation!)].toSet(),
onMapCreated: (GoogleMapController controller) {
if (Theme.of(context).brightness != Brightness.light) controller.setMapStyle(MapStyles.darkMap);
},
Expand All @@ -144,12 +149,12 @@ class _BookScreenState extends State<BookScreen> {
}

List<Widget> buildPersistentFooterButtons() {
if (_book!.userUid != Provider.of<UserModel>(context).uid)
if (book.userUid != Provider.of<UserModel>(context).uid)
return <Widget>[
ElevatedButton(
child: Text(S.current.getInTouchWithSeller),
onPressed: () async {
final ChatModel? chat = await ChatProvider.getChat(_book!.userUid, Provider.of<UserModel>(context, listen: false).uid!);
final ChatModel? chat = await ChatProvider.getChat(book.userUid, Provider.of<UserModel>(context, listen: false).uid!);

if (chat != null) Navigator.of(context).pushNamed(ChatScreen.route, arguments: chat);
},
Expand All @@ -159,7 +164,7 @@ class _BookScreenState extends State<BookScreen> {
return <Widget>[
TextButton(
child: Text(S.current.editInsertion),
onPressed: () => Navigator.of(context).pushReplacementNamed(BookEditorScreen.route, arguments: this._book),
onPressed: () => Navigator.of(context).pushReplacementNamed(BookEditorScreen.route, arguments: this.book),
),
ElevatedButton(
child: Text(S.current.removeBookFromSell),
Expand Down Expand Up @@ -199,8 +204,9 @@ class _BookScreenState extends State<BookScreen> {
false;

if (delete) {
await BookHelper.removeBookFromSell(this._book!.id!);
await sellBooksBloc.getUserBooks(Provider.of<UserModel>(context, listen: false).uid!,Provider.of<UserModel>(context, listen: false).blockedUids!);
await BookHelper.removeBookFromSell(this.book.id!);
await sellBooksBloc.getUserBooks(
Provider.of<UserModel>(context, listen: false).uid!, Provider.of<UserModel>(context, listen: false).blockedUids!);

Navigator.of(context).pop();
}
Expand Down
10 changes: 6 additions & 4 deletions lib/interface/widget/book_list_element.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class BookListElement extends StatelessWidget {
const BookListElement.sell({
Key? key,
required this.book,
}) : this.widgetType = BookListElementType.SELL,
}) : this.widgetType = BookListElementType.SELL,
this.color = null,
this.showPosition = false,
this.results = null,
Expand All @@ -39,7 +39,7 @@ class BookListElement extends StatelessWidget {
required this.book,
required this.color,
required this.results,
}) : this.widgetType = BookListElementType.WANTED,
}) : this.widgetType = BookListElementType.WANTED,
this.showPosition = false,
super(key: key);

Expand Down Expand Up @@ -86,7 +86,8 @@ class BookListElement extends StatelessWidget {
case BookListElementType.WANTED:
return Icon(Icons.circle, color: this.color);
case BookListElementType.RESULT_WANTED:
if (this.showPosition) return Text(Provider.of<LocationProvider>(context).getDistance(this.book.modelizedLocation).toStringAsFixed(1) + S.current.km);
if (this.showPosition)
return Text(Provider.of<LocationProvider>(context).getDistance(this.book.modelizedLocation!).toStringAsFixed(1) + S.current.km);
break;
}

Expand All @@ -109,7 +110,8 @@ class BookListElement extends StatelessWidget {

if (wantsToRemove) {
await BookHelper.removeBookFromSearch(this.book.id!);
await searchBookBloc.getUserBooks(Provider.of<UserModel>(context, listen: false).uid!, Provider.of<UserModel>(context, listen: false).blockedUids!, Provider.of<LocationProvider>(context, listen: false).lastKnownLocation);
await searchBookBloc.getUserBooks(Provider.of<UserModel>(context, listen: false).uid!, Provider.of<UserModel>(context, listen: false).blockedUids!,
Provider.of<LocationProvider>(context, listen: false).lastKnownLocation);
}
},
child: ExpansionTile(
Expand Down
15 changes: 10 additions & 5 deletions lib/models/book_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@

import 'package:bookaround/models/place_model.dart';
import 'package:bookaround/models/user_model.dart';
import 'package:bookaround/references.dart';
import 'package:bookaround/resources/helper/location_helper.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geoflutterfire_plus/geoflutterfire_plus.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:json_annotation/json_annotation.dart';

Expand All @@ -31,9 +33,14 @@ class BookModel extends ChangeNotifier {
@JsonKey(toJson: LocationHelper.locationToJson)
PlaceModel? location;

Map<String, dynamic>? locationData;
@JsonKey(toJson: LocationHelper.geoFirePointToJson, fromJson: LocationHelper.geoFirePointFromJson)
GeoFirePoint? locationData;

LatLng get modelizedLocation => LatLng((locationData!["geopoint"] as GeoPoint).latitude, (locationData!["geopoint"] as GeoPoint).longitude);
LatLng? get modelizedLocation {
if (this.locationData == null) return null;

return LatLng(this.locationData!.latitude, this.locationData!.longitude);
}

@JsonKey(ignore: true)
UserModel? user;
Expand All @@ -44,8 +51,7 @@ class BookModel extends ChangeNotifier {
@JsonKey(ignore: true)
double? distanceInKms;

@JsonKey(ignore: true)
DocumentReference? reference;
DocumentReference get reference => References.booksCollection.doc(id);

String get authorString {
if (this.authors!.isEmpty)
Expand All @@ -68,7 +74,6 @@ class BookModel extends ChangeNotifier {
this.type,
required this.userUid,
this.addedDateTime,
this.reference,
this.highlighting,
this.pencil,
this.pen,
Expand Down
5 changes: 3 additions & 2 deletions lib/models/book_model.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions lib/models/place_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ class PlaceModel {
factory PlaceModel.fromAddress(Address address) => PlaceModel(
id: address.featureName,
description: address.locality ?? address.adminArea ?? address.countryName ?? address.addressLine,
placeId: address.featureName,
placeReference: address.featureName,
placeId: address.locality,
placeReference: address.adminArea,
);

factory PlaceModel.fromJson(Map<String, dynamic> parsedJson) => _$PlaceModelFromJson(parsedJson);
Expand Down
3 changes: 0 additions & 3 deletions lib/resources/helper/book_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class BookHelper {
if (result.data == null) throw BookNotFoundError();

final BookModel response = BookModel.fromJson(jsonDecode(result.data));
response.reference = References.booksCollection.doc(response.id);

debugPrint("Ho caricato nel database il libro $isbn per conto di $currentUserUid.");
return response;
Expand All @@ -37,8 +36,6 @@ class BookHelper {
final DocumentReference bookReference = References.booksCollection.doc(book.id);
await bookReference.set(book.toJson());

book.reference = bookReference;

debugPrint("Aggiunto alle ricerche ${book.secureIsbn}.");
return book;
}
Expand Down
Loading

0 comments on commit 2a58e8f

Please sign in to comment.