Merge remote-tracking branch 'refs/remotes/origin/feature_blogPosts'

# Conflicts:
#	lib/app_router.dart
#	lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart
#	pubspec.yaml
This commit is contained in:
mso7nueh
2024-07-31 13:34:47 +03:00
33 changed files with 940 additions and 202 deletions

View File

@@ -294,7 +294,7 @@ class BlogPostScreen extends StatelessWidget {
void tapMenu(String value, BuildContext context, BlogPostStateLoaded state) {
if (value == 'edit') {
GoRouter.of(context).goNamed(
GoRouter.of(context).pushNamed(
'blogPostEditScreen',
extra: state.blogPost.id.toString(),
);

View File

@@ -8,6 +8,6 @@ part 'blog_post_service.g.dart';
abstract class BlogPostService {
factory BlogPostService(Dio dio, {String baseUrl}) = _BlogPostService;
@GET('/api/feed/show/{id}')
@GET('/api/blogPosts/show/{id}')
Future<BlogPostModel> getBlogPost(@Path() String id);
}

View File

@@ -32,7 +32,7 @@ class _BlogPostService implements BlogPostService {
)
.compose(
_dio.options,
'/api/feed/show/${id}',
'/api/blogPosts/show/${id}',
queryParameters: queryParameters,
data: _data,
)

View File

@@ -1,27 +1,31 @@
/*
import '../../../../presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart';
import '../../../../presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:eatvio_app/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/widgets/custom_outlined_button.dart';
import 'dart:io';
class BlogPostCreateScreen extends StatelessWidget {
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/widgets/custom_outlined_button.dart';
import 'package:eatvio_app/widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../../../presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart';
import '../../../../presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart';
class BlogPostCreateScreen extends StatefulWidget {
const BlogPostCreateScreen({Key? key}) : super(key: key);
static Widget builder(BuildContext context) {
final blog_postID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<BlogPostCreateBloc>(
create: (context) => BlogPostCreateBloc(BlogPostCreateState(
blog_postModelObj:
BlogPostCreateModel(blog_postID: blog_postID.toString())))
create: (context) => BlogPostCreateBloc(BlogPostCreateState(blog_postModelObj: BlogPostCreateModel(blog_postID: blog_postID.toString())))
..add(BlogPostCreateInitialEvent()),
child: BlogPostCreateScreen(),
);
}
@override
State<BlogPostCreateScreen> createState() => _BlogPostCreateScreenState();
}
class _BlogPostCreateScreenState extends State<BlogPostCreateScreen> {
Widget build(BuildContext context) {
return BlocBuilder<BlogPostCreateBloc, BlogPostCreateState>(
builder: (context, state) {
@@ -45,7 +49,6 @@ class BlogPostCreateScreen extends StatelessWidget {
}
_buildBlogPostCreate(BuildContext context, BlogPostCreateLoadedState state) {
print(state.image);
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
@@ -78,15 +81,13 @@ class BlogPostCreateScreen extends StatelessWidget {
children: [
Column(
children: <Widget>[
Text("Заголовок новости",
style: theme.textTheme.bodyLarge),
Text("Заголовок новости", style: theme.textTheme.bodyLarge),
CustomTextFormField(
controller: state.title,
validator: _validateTitle,
),
SizedBox(height: 8.0),
Text("Ссылка на YouTube",
style: theme.textTheme.bodyLarge),
Text("Ссылка на YouTube", style: theme.textTheme.bodyLarge),
CustomTextFormField(
controller: state.youtubeURL,
validator: _validateYouTubeLink,
@@ -103,8 +104,7 @@ class BlogPostCreateScreen extends StatelessWidget {
SizedBox(height: 16.0),
// Add widget for image upload here
CustomOutlinedButton(
onPressed: () => _submitForm(context, state.title!.text,
state.description!.text, state.youtubeURL!.text),
onPressed: () => _submitForm(context, state.title!.text, state.description!.text, state.youtubeURL!.text),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
text: 'Создать',
),
@@ -120,20 +120,16 @@ class BlogPostCreateScreen extends StatelessWidget {
}
}
_submitForm(
BuildContext context, String title, String description, String youtubeURL) {
_submitForm(BuildContext context, String title, String description, String youtubeURL) async {
String? titleError = _validateTitle(title);
String? descriptionError = _validateDescription(description);
String? youtubeURLError = _validateYouTubeLink(youtubeURL);
if (titleError != null ||
descriptionError != null ||
youtubeURLError != null) {
if (titleError != null || descriptionError != null || youtubeURLError != null) {
// Display error messages or handle invalid input as needed
// For example, show a snackbar with the error message
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(titleError ?? descriptionError ?? youtubeURLError!)),
SnackBar(content: Text(titleError ?? descriptionError ?? youtubeURLError!)),
);
} else {
// Proceed with form submission
@@ -200,11 +196,9 @@ addImage(BuildContext context, bool isLoading) {
if (!isLoading) {
return () async {
final picker = ImagePicker();
List<XFile>? images = await picker.pickMultiImage();
if (images.isNotEmpty) {
for (var image in images) {
context.read<BlogPostCreateBloc>().add(UploadImages(image));
}
XFile? image = await picker.pickImage(source: ImageSource.gallery);
if (image != null) {
context.read<BlogPostCreateBloc>().add(UploadImages(image));
}
};
}
@@ -234,8 +228,6 @@ String? _validateYouTubeLink(value) {
}
bool _isValidUrl(String url) {
final RegExp urlRegExp =
new RegExp(r"^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$");
final RegExp urlRegExp = new RegExp(r"^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$");
return urlRegExp.hasMatch(url);
}
*/

View File

@@ -37,7 +37,6 @@ class ChatSelectScreen extends StatelessWidget {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
forceMaterialTransparency: true,
toolbarHeight: 0,
),
body: NestedScrollView(
@@ -48,7 +47,7 @@ class ChatSelectScreen extends StatelessWidget {
sliver: SliverAppBar(
automaticallyImplyLeading: false,
stretchTriggerOffset: 1,
forceMaterialTransparency: true,
scrolledUnderElevation: 0,
floating: true,
snap: true,
title: Padding(

View File

@@ -8,7 +8,6 @@ class FeedCubit extends Cubit<FeedState> {
FeedCubit({required this.feedRepository}) : super(const FeedState.loading());
loadFeedBlogPostList() async {
emit(const FeedState.loading());
try {
final feedBlogPostList = await feedRepository.getFeedBlogPostList();
emit(FeedState.loaded(feedBlogPostList: feedBlogPostList));

View File

@@ -108,7 +108,7 @@ class FeedScreen extends StatelessWidget {
flex: 1,
child: CustomOutlinedButton(
text: "+",
onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'),
onPressed: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
),

View File

@@ -0,0 +1,214 @@
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_widget.dart';
import 'package:eatvio_app/theme/theme_helper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class FeedScreenNew extends StatefulWidget {
const FeedScreenNew({super.key});
@override
State<FeedScreenNew> createState() => _FeedScreenNewState();
}
class _FeedScreenNewState extends State<FeedScreenNew> {
final List<String> chipsLabelList = ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты'];
int _selectedChipIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
toolbarHeight: 0,
systemOverlayStyle: SystemUiOverlayStyle(
statusBarColor: Colors.white,
),
),
backgroundColor: Colors.grey.shade200,
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [
SliverAppBar(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(bottom: Radius.circular(12)),
),
backgroundColor: Colors.white,
foregroundColor: Colors.white,
automaticallyImplyLeading: false,
stretchTriggerOffset: 1,
floating: true,
snap: true,
scrolledUnderElevation: 0,
bottom: _chipGroup(),
title: Row(
children: [
_searchBar(),
SizedBox(width: 12),
_addBlogPostButton(),
],
),
),
];
},
body: _buildAllBlogPosts(),
),
);
}
_buildAllBlogPosts() {
return RefreshIndicator(
onRefresh: () => context.read<FeedCubit>().loadFeedBlogPostList(),
child: BlocBuilder<FeedCubit, FeedState>(
builder: (BuildContext context, FeedState state) {
if (state is FeedStateLoaded) {
return ListView.separated(
padding: EdgeInsets.symmetric(vertical: 8),
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]);
},
separatorBuilder: (context, index) {
return SizedBox(height: 8);
},
itemCount: state.feedBlogPostList.length,
);
} else if (state is FeedStateError) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: Text(state.errorMessage),
),
),
);
} else {
return Scaffold(
body: Center(
child: CupertinoActivityIndicator(),
),
);
}
},
),
);
}
_chipGroup() {
return PreferredSize(
preferredSize: Size(MediaQuery.of(context).size.width, 32),
child: Align(
alignment: Alignment.centerLeft,
child: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: 16),
scrollDirection: Axis.horizontal,
child: Row(
children: [
_choiceChipWidget(0),
SizedBox(width: 8),
_choiceChipWidget(1),
SizedBox(width: 8),
_choiceChipWidget(2),
SizedBox(width: 8),
_choiceChipWidget(3),
SizedBox(width: 8),
_choiceChipWidget(4),
],
),
),
),
);
}
_addBlogPostButton() {
return InkWell(
onTap: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'),
borderRadius: BorderRadius.circular(64),
child: Ink(
decoration: BoxDecoration(
color: appTheme.blueA400,
shape: BoxShape.circle,
),
child: Icon(
Icons.add_rounded,
color: appTheme.gray100,
),
width: 40,
height: 40,
),
);
}
_searchBar() {
return SizedBox(
height: 40,
width: MediaQuery.of(context).size.width - 84,
child: TextFormField(
style: TextStyle(
fontSize: 12,
),
decoration: InputDecoration(
hintText: 'Поиск',
hintStyle: TextStyle(
fontSize: 12,
color: appTheme.gray600,
fontWeight: FontWeight.w400,
),
prefixIcon: Icon(
Icons.search,
color: appTheme.gray600,
size: 16,
),
isDense: false,
contentPadding: EdgeInsets.all(8),
fillColor: appTheme.gray100,
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
),
),
);
}
_choiceChipWidget(int index) {
return ChoiceChip(
selectedColor: appTheme.blueA400,
pressElevation: 0,
showCheckmark: false,
side: BorderSide.none,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
label: Text(chipsLabelList[index]),
labelStyle: TextStyle(
color: index == _selectedChipIndex ? Colors.white : appTheme.gray600,
fontWeight: FontWeight.w500,
fontSize: 12,
),
selected: _selectedChipIndex == index,
backgroundColor: appTheme.gray100,
onSelected: (bool selected) {
setState(() {
_selectedChipIndex = index;
});
},
);
}
}

View File

@@ -0,0 +1,133 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class BlogPostWidget extends StatefulWidget {
final FeedBlogPostModel feedBlogPostModel;
const BlogPostWidget({super.key, required this.feedBlogPostModel});
@override
State<BlogPostWidget> createState() => _BlogPostWidgetState();
}
class _BlogPostWidgetState extends State<BlogPostWidget> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => GoRouter.of(context).pushNamed(
'blogPostScreen',
extra: widget.feedBlogPostModel.id.toString(),
),
child: Ink(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.white,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
CircleAvatar(radius: 20),
SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Имя автора'),
Text('Время поста'),
],
),
],
),
),
if (widget.feedBlogPostModel.title.isNotEmpty || widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text(widget.feedBlogPostModel.title),
),
if (widget.feedBlogPostModel.title.isNotEmpty && widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text(widget.feedBlogPostModel.description),
),
if (widget.feedBlogPostModel.title.isNotEmpty || widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 8),
GestureDetector(
onTap: () {
context.pushTransparentRoute(
rootNavigator: true,
PhotoViewScreen(
imageUrls: [baseUrl + '/storage/' + widget.feedBlogPostModel.image],
index: 0,
),
);
},
child: Hero(
tag: baseUrl + '/storage/' + widget.feedBlogPostModel.image,
child: CachedNetworkImage(
imageUrl: baseUrl + '/storage/' + widget.feedBlogPostModel.image,
),
),
),
SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
_iconButton(Icons.favorite_border_rounded),
SizedBox(width: 8),
_iconButton(Icons.mode_comment_outlined),
SizedBox(width: 8),
_iconButton(Icons.reply_rounded),
],
),
),
SizedBox(height: 8),
],
),
),
);
}
_iconButton(IconData icon, [String? text]) {
return InkWell(
onTap: () {},
borderRadius: BorderRadius.circular(16),
child: Ink(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: appTheme.gray100,
borderRadius: BorderRadius.circular(16),
),
height: 32,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: 20,
color: appTheme.gray600,
),
if (text != null) SizedBox(width: 8),
if (text != null)
Text(
text,
style: TextStyle(
color: appTheme.gray600,
fontWeight: FontWeight.w500,
),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,15 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'location_model.g.dart';
part 'location_model.freezed.dart';
@freezed
class LocationModel with _$LocationModel {
const factory LocationModel({
required List<String> locations,
@JsonKey(name: 'response_body') required String responseBody,
}) = _LocationModel;
factory LocationModel.fromJson(Map<String, Object?> json) => _$LocationModelFromJson(json);
}

View File

@@ -0,0 +1,189 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'location_model.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
LocationModel _$LocationModelFromJson(Map<String, dynamic> json) {
return _LocationModel.fromJson(json);
}
/// @nodoc
mixin _$LocationModel {
List<String> get locations => throw _privateConstructorUsedError;
@JsonKey(name: 'response_body')
String get responseBody => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$LocationModelCopyWith<LocationModel> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $LocationModelCopyWith<$Res> {
factory $LocationModelCopyWith(
LocationModel value, $Res Function(LocationModel) then) =
_$LocationModelCopyWithImpl<$Res, LocationModel>;
@useResult
$Res call(
{List<String> locations,
@JsonKey(name: 'response_body') String responseBody});
}
/// @nodoc
class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel>
implements $LocationModelCopyWith<$Res> {
_$LocationModelCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? locations = null,
Object? responseBody = null,
}) {
return _then(_value.copyWith(
locations: null == locations
? _value.locations
: locations // ignore: cast_nullable_to_non_nullable
as List<String>,
responseBody: null == responseBody
? _value.responseBody
: responseBody // ignore: cast_nullable_to_non_nullable
as String,
) as $Val);
}
}
/// @nodoc
abstract class _$$LocationModelImplCopyWith<$Res>
implements $LocationModelCopyWith<$Res> {
factory _$$LocationModelImplCopyWith(
_$LocationModelImpl value, $Res Function(_$LocationModelImpl) then) =
__$$LocationModelImplCopyWithImpl<$Res>;
@override
@useResult
$Res call(
{List<String> locations,
@JsonKey(name: 'response_body') String responseBody});
}
/// @nodoc
class __$$LocationModelImplCopyWithImpl<$Res>
extends _$LocationModelCopyWithImpl<$Res, _$LocationModelImpl>
implements _$$LocationModelImplCopyWith<$Res> {
__$$LocationModelImplCopyWithImpl(
_$LocationModelImpl _value, $Res Function(_$LocationModelImpl) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? locations = null,
Object? responseBody = null,
}) {
return _then(_$LocationModelImpl(
locations: null == locations
? _value._locations
: locations // ignore: cast_nullable_to_non_nullable
as List<String>,
responseBody: null == responseBody
? _value.responseBody
: responseBody // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
@JsonSerializable()
class _$LocationModelImpl implements _LocationModel {
const _$LocationModelImpl(
{required final List<String> locations,
@JsonKey(name: 'response_body') required this.responseBody})
: _locations = locations;
factory _$LocationModelImpl.fromJson(Map<String, dynamic> json) =>
_$$LocationModelImplFromJson(json);
final List<String> _locations;
@override
List<String> get locations {
if (_locations is EqualUnmodifiableListView) return _locations;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_locations);
}
@override
@JsonKey(name: 'response_body')
final String responseBody;
@override
String toString() {
return 'LocationModel(locations: $locations, responseBody: $responseBody)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$LocationModelImpl &&
const DeepCollectionEquality()
.equals(other._locations, _locations) &&
(identical(other.responseBody, responseBody) ||
other.responseBody == responseBody));
}
@JsonKey(ignore: true)
@override
int get hashCode => Object.hash(runtimeType,
const DeepCollectionEquality().hash(_locations), responseBody);
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith =>
__$$LocationModelImplCopyWithImpl<_$LocationModelImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$LocationModelImplToJson(
this,
);
}
}
abstract class _LocationModel implements LocationModel {
const factory _LocationModel(
{required final List<String> locations,
@JsonKey(name: 'response_body') required final String responseBody}) =
_$LocationModelImpl;
factory _LocationModel.fromJson(Map<String, dynamic> json) =
_$LocationModelImpl.fromJson;
@override
List<String> get locations;
@override
@JsonKey(name: 'response_body')
String get responseBody;
@override
@JsonKey(ignore: true)
_$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@@ -0,0 +1,20 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'location_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$LocationModelImpl _$$LocationModelImplFromJson(Map<String, dynamic> json) =>
_$LocationModelImpl(
locations:
(json['locations'] as List<dynamic>).map((e) => e as String).toList(),
responseBody: json['response_body'] as String,
);
Map<String, dynamic> _$$LocationModelImplToJson(_$LocationModelImpl instance) =>
<String, dynamic>{
'locations': instance.locations,
'response_body': instance.responseBody,
};

View File

@@ -21,8 +21,8 @@ class RegistrationCubit extends Cubit<RegistrationState> {
passwordConfirmation: '',
birthdate: '',
gender: '',
country: '',
city: '',
location: '',
responseBody: '',
lang: '',
weight: 0,
height: 0,
@@ -54,4 +54,24 @@ class RegistrationCubit extends Cubit<RegistrationState> {
rethrow;
}
}
Future<List<String>> getLocationsByQuery(String query) async {
try {
final location = (await registrationRepository.getLocationsListByQuery(query));
emit(RegistrationState(sheet: state.sheet.copyWith(responseBody: location.responseBody)));
return location.locations;
} catch (e) {
rethrow;
}
}
Future<List<String>> getLocationsByCoordinates(String latitude, String longitude) async {
try {
final location = (await registrationRepository.getLocationsListByCoordinates(latitude, longitude));
emit(RegistrationState(sheet: state.sheet.copyWith(responseBody: location.responseBody)));
return location.locations;
} catch (e) {
rethrow;
}
}
}

View File

@@ -1,11 +1,11 @@
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart';
import 'package:eatvio_app/features/registration/consts/cities_list.dart';
import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart';
import 'package:eatvio_app/widgets/custom_drop_down.dart';
import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:location/location.dart';
class CityOfLivingScreen extends StatefulWidget {
final UserRegistrationSheet sheet;
@@ -23,20 +23,43 @@ class _CityOfLivingScreenState extends State<CityOfLivingScreen> {
late SelectionPopupModel selectedItem;
final cityController = TextEditingController();
final suggestionsController = SuggestionsController<String>();
bool isLoading = false;
@override
void initState() {
super.initState();
if (widget.sheet.country.isNotEmpty) {
selectedItem = dropdownItemList.firstWhere((item) => item.title == widget.sheet.country);
} else {
selectedItem = dropdownItemList.first;
final registrationCubit = context.read<RegistrationCubit>();
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: selectedItem.title));
if (widget.sheet.location.isNotEmpty) {
cityController.text = widget.sheet.location;
}
if (widget.sheet.city.isNotEmpty) {
cityController.text = widget.sheet.city;
}
Future<LocationData?> getLocationData() async {
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
LocationData _locationData;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return null;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return null;
}
}
_locationData = await location.getLocation();
return _locationData;
}
@override
@@ -46,61 +69,91 @@ class _CityOfLivingScreenState extends State<CityOfLivingScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("country".tr),
Text("Местоположение"),
SizedBox(height: 4),
CustomDropDown(
icon: Container(
margin: EdgeInsets.fromLTRB(30.h, 11.v, 17.h, 11.v),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)),
child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),
),
hintText: "Не выбрано".tr,
items: dropdownItemList,
value: selectedItem,
onChanged: (newValue) {
setState(() {
selectedItem = newValue;
});
final registrationCubit = context.read<RegistrationCubit>();
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: newValue.title));
},
),
SizedBox(height: 16),
Text("Населенный пункт"),
SizedBox(height: 4),
TypeAheadField(
debounceDuration: Duration.zero,
controller: cityController,
builder: (context, controller, focus) => CustomTextFormField(
controller: cityController,
focusNode: focus,
textStyle: TextStyle(
fontSize: 16,
color: Colors.black,
)
),
itemBuilder: (BuildContext context, String item) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item, style: theme.textTheme.bodyLarge?.copyWith(color: Colors.black)),
);
},
decorationBuilder: (context, child) => Material(
type: MaterialType.card,
elevation: 4,
borderRadius: BorderRadius.circular(8),
child: child,
),
onSelected: (item) {
setState(() {
cityController.text = item;
});
final registrationCubit = context.read<RegistrationCubit>();
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(city: item));
},
suggestionsCallback: (query) {
return citiesList.where((country) => country.toLowerCase().contains(query.toLowerCase())).toList();
},
Row(
children: [
SizedBox(
width: MediaQuery.of(context).size.width - 80,
child: TypeAheadField(
debounceDuration: Duration(milliseconds: 300),
controller: cityController,
suggestionsController: suggestionsController,
builder: (context, controller, focus) => CustomTextFormField(
controller: cityController,
focusNode: focus,
autofocus: true,
textStyle: TextStyle(
fontSize: 16,
color: Colors.black,
)),
itemBuilder: (BuildContext context, String item) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item, style: theme.textTheme.bodyLarge?.copyWith(color: Colors.black)),
);
},
decorationBuilder: (context, child) => Material(
type: MaterialType.card,
elevation: 4,
borderRadius: BorderRadius.circular(8),
child: child,
),
onSelected: (item) {
setState(() {
cityController.text = item;
});
final registrationCubit = context.read<RegistrationCubit>();
registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(location: item));
},
suggestionsCallback: (query) async {
if (query.length >= 3) {
final registrationCubit = context.read<RegistrationCubit>();
return (await registrationCubit.getLocationsByQuery(query));
}
return null;
},
),
),
SizedBox(width: 8),
InkWell(
borderRadius: BorderRadius.circular(8),
onTap: !isLoading
? () async {
setState(() {
isLoading = true;
});
final LocationData? locationData = await getLocationData();
if (locationData != null) {
final List<String> locations = await context
.read<RegistrationCubit>()
.getLocationsByCoordinates(locationData.latitude.toString(), locationData.longitude.toString());
setState(() {
cityController.text = locations.first;
suggestionsController.suggestions = locations;
});
}
setState(() {
isLoading = false;
});
}
: null,
child: Ink(
height: 40,
width: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Color(0xFFEAF2FD),
),
child: !isLoading
? Icon(
Icons.near_me_rounded,
color: appTheme.blueA400,
)
: CupertinoActivityIndicator(),
),
),
],
),
],
),

View File

@@ -244,7 +244,7 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
return false;
}
case 6:
if (state.sheet.country.isNotEmpty && state.sheet.city.isNotEmpty)
if (state.sheet.location.isNotEmpty)
return true;
else {
showDialog(

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart';
import 'package:eatvio_app/features/registration/models/location_model.dart';
import 'package:eatvio_app/features/registration/services/registration_service.dart';
class RegistrationRepository {
@@ -13,4 +14,20 @@ class RegistrationRepository {
rethrow;
}
}
Future<LocationModel> getLocationsListByQuery(String query) async {
try {
return (await registrationService.getLocationsByAddress(query: query));
} catch (e) {
rethrow;
}
}
Future<LocationModel> getLocationsListByCoordinates(String latitude, String longitude) async {
try {
return (await registrationService.getLocationsByCoordinate(latitude: latitude, longitude: longitude));
} catch (e) {
rethrow;
}
}
}

View File

@@ -1,4 +1,5 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/registration/models/location_model.dart';
import 'package:retrofit/retrofit.dart';
part 'registration_service.g.dart';
@@ -11,4 +12,15 @@ abstract class RegistrationService {
Future<Map<String, String>> register({
@Body() required Map<String, dynamic> sheet,
});
@GET('/api/location_by_address')
Future<LocationModel> getLocationsByAddress({
@Query('user_address') required String query,
});
@GET('/api/location_by_coordinate')
Future<LocationModel> getLocationsByCoordinate({
@Query('coordinate[position][latitude]') required String latitude,
@Query('coordinate[position][longitude]') required String longitude,
});
}

View File

@@ -47,6 +47,66 @@ class _RegistrationService implements RegistrationService {
return _value;
}
@override
Future<LocationModel> getLocationsByAddress({required String query}) async {
final _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{r'user_address': query};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<LocationModel>(Options(
method: 'GET',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/api/location_by_address',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = LocationModel.fromJson(_result.data!);
return _value;
}
@override
Future<LocationModel> getLocationsByCoordinate({
required String latitude,
required String longitude,
}) async {
final _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{
r'coordinate[position][latitude]': latitude,
r'coordinate[position][longitude]': longitude,
};
final _headers = <String, dynamic>{};
const Map<String, dynamic>? _data = null;
final _result = await _dio
.fetch<Map<String, dynamic>>(_setStreamType<LocationModel>(Options(
method: 'GET',
headers: _headers,
extra: _extra,
)
.compose(
_dio.options,
'/api/location_by_coordinate',
queryParameters: queryParameters,
data: _data,
)
.copyWith(
baseUrl: _combineBaseUrls(
_dio.options.baseUrl,
baseUrl,
))));
final _value = LocationModel.fromJson(_result.data!);
return _value;
}
RequestOptions _setStreamType<T>(RequestOptions requestOptions) {
if (T != dynamic &&
!(requestOptions.responseType == ResponseType.bytes ||