Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Chat Bloc Fixed
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/chat_page/chat.dart';
import 'package:flutter_app/network/request/send_message_request.dart';
import 'package:flutter_app/network/response/message_response.dart';
import 'package:flutter_app/network/response/send_message_response.dart';
import 'package:flutter_app/network/service/base_call_back.dart';
import 'package:flutter_app/network/service/network_factory.dart';
class ChatBloc extends Bloc<ChatEvent, ChatState> {
NetworkFactory _networkFactory;
BuildContext context;
ChatBloc(this.context) {
_networkFactory = NetworkFactory();
}
@override
ChatState get initialState => ChatInitial();
@override
void onTransition(Transition<ChatEvent, ChatState> transition) {
print(transition);
}
@override
Stream<ChatState> mapEventToState(
ChatState currentState, ChatEvent event) async* {
if (event is SendMessageEvent) {
MessagesResponse newMessage = event.newMessage;
var service = await _networkFactory.apiService();
BaseCallBack baseCallBack = BaseCallBack();
ChatState state = await baseCallBack
.getDataFromApi(
context,
_networkFactory,
service.sendMessage(
'475931182756946',
'st_2678107838882712',
SendMessageRequest(
data: MessageData(
message: newMessage.fbmsg,
tempId: 'st_2678107838882712' +
'${newMessage.fbcreatedTime}'))
.toJson()))
.map((data) => _handleSendMessage(data, event))
.first;
yield state;
}
}
ChatState _handleSendMessage(data, SendMessageEvent event) {
if (data is String) {
return SendMessageFail(error: data, message: event.newMessage);
} else {
SendMessageResponseEntity response =
SendMessageResponseEntity.fromJson(data);
if (response != null) {
return SendMessageSuccess(message: event.newMessage);
} else {
return SendMessageFail(error: "Send messages fail");
}
}
}
void dispose() {
_networkFactory.closeService();
super.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.