feat(chat, feed): add images, chat search, likes reply to comment

This commit is contained in:
mso7nueh
2024-08-21 16:24:53 +03:00
parent 892fdbebb8
commit 8349778e48
24 changed files with 2213 additions and 445 deletions

View File

@@ -0,0 +1,111 @@
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chat_select_cubit/chat_select_cubit.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chat_select_cubit/chat_select_state.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/chat_entry_widget.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/chat_search_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ChatSelectScreen extends StatefulWidget {
const ChatSelectScreen({Key? key}) : super(key: key);
@override
State<ChatSelectScreen> createState() => _ChatSelectScreenState();
}
class _ChatSelectScreenState extends State<ChatSelectScreen> {
final searchController = TextEditingController();
Widget build(BuildContext context) {
return BlocBuilder<ChatSelectCubit, ChatSelectState>(
builder: (context, state) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
toolbarHeight: 0,
),
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [
SliverPadding(
padding: const EdgeInsets.only(top: 8),
sliver: SliverAppBar(
automaticallyImplyLeading: false,
stretchTriggerOffset: 1,
scrolledUnderElevation: 0,
floating: true,
snap: true,
title: Padding(
padding: const EdgeInsets.only(top: 8),
child: ChatSearchBarWidget(
onChanged: (query) {
if (query.length > 2) {
EasyDebounce.debounce(
'searchChatRoom',
Duration(milliseconds: 300),
() => context.read<ChatSelectCubit>().getChatRooms(query: query),
);
} else {
context.read<ChatSelectCubit>().getChatRooms();
}
},
controller: searchController,
fillColor: Color(0xFFF0F2F5),
hintText: "Поиск",
hintStyle: TextStyle(
color: Color(0xFF7B8794),
),
),
),
),
),
];
},
body: stateBuilder(state),
),
);
},
);
}
stateBuilder(state) {
if (state is ChatSelectStateLoading) {
return Scaffold(
body: Center(
child: CupertinoActivityIndicator(),
),
);
} else if (state is ChatSelectStateLoaded) {
return _buildChatList(context, state);
} else if (state is ChatSelectStateError) {
return Padding(
padding: const EdgeInsets.all(16),
child: Center(child: Text(state.errorMessage)),
);
} else {
return Scaffold(
body: Center(
child: CupertinoActivityIndicator(),
),
);
}
}
}
_buildChatList(BuildContext context, ChatSelectStateLoaded state) {
return ListView.separated(
padding: EdgeInsets.all(16),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
separatorBuilder: (context, index) {
return SizedBox(
height: 8,
);
},
itemCount: state.chatRooms.length,
itemBuilder: (context, index) {
return ChatEntryWidget(chatRoom: state.chatRooms[index]);
},
);
}

View File

@@ -1,100 +0,0 @@
import 'dart:convert';
import 'package:eatvio_app/app_router.dart';
import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart';
import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import '/core/app_export.dart';
part 'chat_select_event.dart';
part 'chat_select_state.dart';
/// A bloc that manages the state of a ChatSelect according to the event that is dispatched to it.
///
class ChatSelectBloc extends Bloc<ChatSelectEvent, ChatSelectState> {
ChatSelectBloc(ChatSelectState initialState) : super(initialState) {
on<ChatSelectInitialEvent>(_onInitialize);
}
List<ChatItemModel> fillChatEntryList(List<dynamic> chatRooms) {
List<ChatItemModel> chats = [];
for (int i = 0; i < chatRooms.length; i++) {
String text = chatRooms[i]['last_message'] is List ? '' : chatRooms[i]['last_message']['data'];
if (chatRooms[i]['last_message'] is! List && chatRooms[i]['last_message']['is_author_message_auth_user'] != null) {
text = "Вы: " + text;
}
chats.add(
ChatItemModel(
id: chatRooms[i]['id'],
username: chatRooms[i]['users']['to_chat_user']['name'],
dateText: chatRooms[i]['last_message'] is List
? ''
: DateFormat('dd.MM').format(
DateTime.parse(
chatRooms[i]['last_message']['updated_at'],
),
),
greetingText: text,
),
);
}
return chats;
}
Future<void> _onInitialize(
ChatSelectInitialEvent event,
Emitter<ChatSelectState> emit,
) async {
try {
final box = await Hive.openBox('token');
final token = box.get('token');
if (token == null) {
AppRouter.navigatorKey.currentContext?.goNamed('authScreen');
}
final response = await http.get(
Uri.parse(baseUrl + '/api/chat/index'),
headers: {
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data is Map<String, dynamic> && data.containsKey('chatRooms')) {
if (state is ChatSelectLoadedState) {
var currentState = state as ChatSelectLoadedState;
emit(
currentState.copyWith(
chatSelectModelObj: currentState.chatSelectModelObj,
chatRooms: currentState.chatRooms,
),
);
} else {
emit(
ChatSelectLoadedState(
chatRooms: fillChatEntryList(data['chatRooms']),
//chatRooms: [],
),
);
}
} else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
emit(ChatSelectErrorState('Некоторые необходимые данные отсутствуют.'));
}
} else {
// Статус ответа не равен 200, обрабатываем ошибку
emit(ChatSelectErrorState('Ошибка сервера: ${response.statusCode}'));
}
} catch (e) {
// Ошибка при декодировании JSON или другая ошибка выполнения
emit(ChatSelectErrorState('Ошибка при получении данных о чатах: $e'));
}
}
}

View File

@@ -1,28 +0,0 @@
// ignore_for_file: must_be_immutable
part of 'chat_select_bloc.dart';
/// Abstract class for all events that can be dispatched from the
///ChatSelect widget.
///
/// Events must be immutable and implement the [Equatable] interface.
@immutable
abstract class ChatSelectEvent extends Equatable {}
/// Event that is dispatched when the ChatSelect widget is first created.
class ChatSelectInitialEvent extends ChatSelectEvent {
@override
List<Object?> get props => [];
}
///event for dropdown selection
class ChangeDropDownEvent extends ChatSelectEvent {
ChangeDropDownEvent({required this.value});
SelectionPopupModel value;
@override
List<Object?> get props => [
value,
];
}

View File

@@ -1,61 +0,0 @@
// ignore_for_file: must_be_immutable
part of 'chat_select_bloc.dart';
/// Represents the state of ChatSelect in the application.
class ChatSelectState extends Equatable {
ChatSelectState({
this.chatSelectModelObj,
});
ChatSelectModel? chatSelectModelObj;
@override
List<Object?> get props => [chatSelectModelObj];
ChatSelectState copyWith({ChatSelectModel? chatSelectModelObj}) {
return ChatSelectState(
chatSelectModelObj: chatSelectModelObj ?? this.chatSelectModelObj,
);
}
}
class ChatSelectInitialState extends ChatSelectState {
ChatSelectInitialState({required ChatSelectModel chatSelectModelObj}) : super(chatSelectModelObj: chatSelectModelObj);
}
class ChatSelectLoadedState extends ChatSelectState {
ChatSelectLoadedState({
this.chatRooms,
this.searchController,
this.chatSelectModelObj,
}) : super(chatSelectModelObj: null);
List<dynamic>? chatRooms;
TextEditingController? searchController;
ChatSelectModel? chatSelectModelObj;
@override
List<Object?> get props => [chatSelectModelObj, chatRooms, searchController];
ChatSelectLoadedState copyWith({
ChatSelectModel? chatSelectModelObj,
TextEditingController? searchController,
List<dynamic>? chatRooms,
}) {
return ChatSelectLoadedState(
chatSelectModelObj: chatSelectModelObj ?? this.chatSelectModelObj,
chatRooms: chatRooms ?? this.chatRooms,
searchController: searchController ?? this.searchController,
);
}
}
class ChatSelectErrorState extends ChatSelectState {
final String errorMessage;
ChatSelectErrorState(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}

View File

@@ -1,144 +0,0 @@
import 'package:eatvio_app/core/app_export.dart';
import 'package:flutter/material.dart';
class CustomSearchView extends StatelessWidget {
CustomSearchView({
Key? key,
this.alignment,
this.width,
this.scrollPadding,
this.controller,
this.focusNode,
this.autofocus = false,
this.textStyle,
this.textInputType = TextInputType.text,
this.maxLines,
this.hintText,
this.hintStyle,
this.prefix,
this.prefixConstraints,
this.suffix,
this.suffixConstraints,
this.contentPadding,
this.borderDecoration,
this.fillColor,
this.filled = true,
this.validator,
this.onChanged,
}) : super(key: key);
final Alignment? alignment;
final double? width;
final TextEditingController? scrollPadding;
final TextEditingController? controller;
final FocusNode? focusNode;
final bool? autofocus;
final TextStyle? textStyle;
final TextInputType? textInputType;
final int? maxLines;
final String? hintText;
final TextStyle? hintStyle;
final Widget? prefix;
final BoxConstraints? prefixConstraints;
final Widget? suffix;
final BoxConstraints? suffixConstraints;
final EdgeInsets? contentPadding;
final InputBorder? borderDecoration;
final Color? fillColor;
final bool? filled;
final FormFieldValidator<String>? validator;
final Function(String)? onChanged;
@override
Widget build(BuildContext context) {
return searchViewWidget(context);
}
searchViewWidget(BuildContext context) => SizedBox(
width: width ?? double.maxFinite,
child: TextFormField(
controller: controller,
focusNode: focusNode,
onTapOutside: (event) => onTapOutside(),
autofocus: autofocus!,
style: textStyle ?? CustomTextStyles.bodySmallMulishBluegray800,
keyboardType: textInputType,
maxLines: maxLines ?? 1,
decoration: decoration,
validator: validator,
onChanged: (String value) => onChanged?.call(value),
),
);
void onTapOutside() {
if (focusNode != null) {
focusNode?.unfocus();
} else {
FocusManager.instance.primaryFocus?.unfocus();
}
}
InputDecoration get decoration => InputDecoration(
hintText: hintText ?? "",
hintStyle: hintStyle ?? CustomTextStyles.bodySmallMulishBluegray800,
prefixIcon: prefix ??
Padding(
padding: EdgeInsets.only(left: 12),
child: Icon(
Icons.search,
color: Color(0xFF7B8794),
),
),
suffixIcon: suffix ??
IconButton(
onPressed: () => controller!.clear(),
icon: Icon(
Icons.clear,
color: Colors.grey.shade600,
),
),
suffixIconConstraints: suffixConstraints ??
BoxConstraints(
maxHeight: 40.v,
),
isDense: true,
contentPadding: EdgeInsets.all(16),
fillColor: fillColor ?? appTheme.gray100,
filled: filled,
border: borderDecoration ??
OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
enabledBorder: borderDecoration ??
OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
focusedBorder: borderDecoration ??
OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
);
}

View File

@@ -1,103 +0,0 @@
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart';
import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/widgets/chat_entry_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'bloc/chat_select_bloc.dart';
import 'chat_search_view.dart';
import 'models/chat_select_model.dart';
class ChatSelectScreen extends StatelessWidget {
const ChatSelectScreen({Key? key}) : super(key: key);
static Widget builder(BuildContext context) {
return BlocProvider<ChatSelectBloc>(
create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()),
child: ChatSelectScreen(),
);
}
Widget build(BuildContext context) {
return BlocBuilder<ChatSelectBloc, ChatSelectState>(
builder: (context, state) {
if (state is ChatSelectInitialState) {
return Scaffold(
body: Center(
child: CupertinoActivityIndicator(),
),
);
} else if (state is ChatSelectLoadedState) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
toolbarHeight: 0,
),
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [
SliverPadding(
padding: const EdgeInsets.only(top: 8),
sliver: SliverAppBar(
automaticallyImplyLeading: false,
stretchTriggerOffset: 1,
scrolledUnderElevation: 0,
floating: true,
snap: true,
title: Padding(
padding: const EdgeInsets.only(top: 8),
child: CustomSearchView(
onChanged: (query) {
},
controller: state.searchController,
fillColor: Color(0xFFF0F2F5),
hintText: "Поиск",
hintStyle: TextStyle(
color: Color(0xFF7B8794),
),
),
),
),
),
];
},
body: _buildChatList(context, state),
),
);
} else if (state is ChatSelectErrorState) {
return Padding(
padding: const EdgeInsets.all(16),
child: Center(child: Text(state.errorMessage)),
);
} else {
return Scaffold(
body: Center(
child: CupertinoActivityIndicator(),
),
);
}
},
);
}
}
_buildChatList(BuildContext context, ChatSelectLoadedState state) {
return ListView.separated(
padding: EdgeInsets.all(16),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
separatorBuilder: (context, index) {
return SizedBox(
height: 8,
);
},
itemCount: state.chatRooms?.length ?? 0,
itemBuilder: (context, index) {
ChatItemModel model = state.chatRooms?[index];
return ChatEntryWidget(
chatEntryObj: model,
);
},
);
}

View File

@@ -1,26 +0,0 @@
import 'package:eatvio_app/core/app_export.dart';
/// This class is used in the [userprofile_item_widget] screen.
// ignore_for_file: must_be_immutable
class ChatItemModel {
String? userImage;
String? username;
String? dateText;
String? greetingText;
String id;
ChatItemModel({
this.userImage,
this.username,
this.dateText,
this.greetingText,
required this.id,
}) {
userImage = userImage ?? ImageConstant.imageNotFound;
username = username;
dateText = dateText;
greetingText = greetingText;
id = id;
}
}

View File

@@ -1,22 +0,0 @@
// ignore_for_file: must_be_immutable
import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart';
import 'package:equatable/equatable.dart';
/// This class defines the variables used in the [chat_select_screen],
/// and is typically used to hold data that is passed between different parts of the application.
class ChatSelectModel extends Equatable {
ChatSelectModel({this.chatList = const []});
List<ChatItemModel> chatList;
ChatSelectModel copyWith({List<ChatItemModel>? chatList}) {
return ChatSelectModel(
chatList: chatList ?? this.chatList,
);
}
@override
List<Object?> get props => [chatList];
}

View File

@@ -1,96 +0,0 @@
// ignore_for_file: must_be_immutable
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class ChatEntryWidget extends StatelessWidget {
ChatEntryWidget({
required this.chatEntryObj,
super.key,
});
ChatItemModel chatEntryObj;
@override
Widget build(BuildContext context) {
return InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () => GoRouter.of(context).pushNamed(
'chatScreen',
extra: chatEntryObj.id.toString(),
),
child: Ink(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: Color(0xFFF6FAFF),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 48,
height: 48,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Color(0xFFEBF4FF),
shape: BoxShape.circle,
),
child: Text(
chatEntryObj.username!.split(' ').first[0] + chatEntryObj.username!.split(' ')[1][0],
style: TextStyle(
color: Color(0xFF7F9CF5),
fontWeight: FontWeight.w400,
fontSize: 20,
),
),
),
SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
chatEntryObj.username!.length <= 15 ? chatEntryObj.username! : chatEntryObj.username!.substring(0, 15) + '...',
style: theme.textTheme.titleMedium,
),
Spacer(),
CustomImageView(
imagePath: ImageConstant.imageNotFound,
height: 9.v,
width: 16.h,
margin: EdgeInsets.only(
top: 4.v,
bottom: 6.v,
),
),
Padding(
padding: EdgeInsets.only(left: 6.h),
child: Text(
chatEntryObj.dateText!,
style: theme.textTheme.bodyMedium,
),
),
],
),
SizedBox(height: 6.v),
Text(
chatEntryObj.greetingText!.trim(),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: CustomTextStyles.bodyMediumBluegray800,
),
],
),
),
],
),
),
);
}
}