i'm learning to use Cubit, Initially the application runs without any errors when I do the likeArticle, but when I do the like method continuously or too often an Unhandled Exception will occur. This my code:
//article_cubit.dart
class ArticleCubit extends Cubit<ArticleState> {
final CreateArticleUseCase createArticleUseCase;
final ReadArticlesUseCase readArticlesUseCase;
final LikeArticleUseCase likeArticleUseCase;
ArticleCubit({
required this.createArticleUseCase,
required this.readArticlesUseCase,
required this.likeArticleUseCase,
}) : super(ArticleInitial());
Future<void> createArticle({required ArticleEntity articleEntity}) async {
try {
await createArticleUseCase.call(articleEntity);
} on SocketException catch (_) {
emit(ArticleFailure());
} catch (_) {
emit(ArticleFailure());
}
}
Future<void> getArticles({required ArticleEntity articleEntity}) async {
emit(ArticleLoading());
try {
final streamResponse = readArticlesUseCase.call(articleEntity);
streamResponse.listen(
(articles) {
debugPrint("ArticleCubit[getArticles]: emit(ArticleLoaded())");
emit(ArticleLoaded(articles: articles));
},
);
} on SocketException catch (_) {
emit(ArticleFailure());
} catch (_) {
emit(ArticleFailure());
}
}
Future<void> likeArticle({required ArticleEntity articleEntity}) async {
try {
await likeArticleUseCase.call(articleEntity);
} on SocketException catch (_) {
emit(ArticleFailure());
} catch (_) {
emit(ArticleFailure());
}
}
}
This my ArticlePage:
class ArticlePage extends StatelessWidget {
final UserEntity currentUser;
const ArticlePage({super.key, required this.currentUser});
@override
Widget build(BuildContext context) {
debugPrint("ArticlePage[build]: Building!!");
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
title: Text(
"Article",
style: TextStyle(color: AppColor.primaryColor, fontSize: 25),
),
actions: [
currentUser.role == "admin"
? Padding(
padding: const EdgeInsets.only(right: 10.0),
child: InkWell(
onTap: () {
Navigator.pushNamed(
context,
PageConst.uploadArticlePage,
arguments: currentUser,
);
},
child: Icon(Icons.create, color: AppColor.primaryColor),
),
)
: const SizedBox(),
],
),
body: BlocProvider<ArticleCubit>(
create: (context) => di.sl<ArticleCubit>()
..getArticles(articleEntity: const ArticleEntity()),
child: BlocBuilder<ArticleCubit, ArticleState>(
builder: (context, articleState) {
if (articleState is ArticleLoading) {
return const Center(
child: CircularProgressIndicator(
color: Colors.black,
));
}
if (articleState is ArticleFailure) {
toast("Some failure occured while creating the article");
}
if (articleState is ArticleLoaded) {
return articleState.articles.isEmpty
? _noPostsWidget()
: ListView.builder(
itemCount: articleState.articles.length,
itemBuilder: (context, index) {
final article = articleState.articles[index];
return BlocProvider(
create: (context) => di.sl<ArticleCubit>(),
child: SingleArticleWidget(articleEntity: article),
);
},
);
}
return const Center(
child: CircularProgressIndicator(
color: Colors.black,
));
},
),
),
);
}
Center _noPostsWidget() {
return Center(
child: Text(
"No Posts",
style: TextStyle(
color: AppColor.primaryColor,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
);
}
}
and this my SingleArticleWidget (like Card widget);
class SingleArticleWidget extends StatefulWidget {
final ArticleEntity articleEntity;
const SingleArticleWidget({
Key? key,
required this.articleEntity,
}) : super(key: key);
@override
State<SingleArticleWidget> createState() => _SingleArticleWidgetState();
}
class _SingleArticleWidgetState extends State<SingleArticleWidget> {
String _currentUid = "";
@override
void initState() {
di.sl<GetCurrentUidUseCase>().call().then((uid) {
setState(() {
_currentUid = uid;
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
offset: const Offset(5, 10),
blurRadius: 10,
color: AppColor.gradientSecond.withOpacity(0.3),
),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 5.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// [TopSection]: Image and title
Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
Navigator.pushNamed(
context,
PageConst.detailArticlePage,
arguments: AppEntity(
uid: _currentUid,
articleId: widget.articleEntity.articleId,
creatorUid: widget.articleEntity.creatorUid,
),
);
},
child: Ink(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Image
Container(
width: double.infinity,
height: size.height * 0.25,
decoration: BoxDecoration(
// color: Colors.red,
borderRadius: BorderRadius.circular(10),
),
child: imageBoxWidget(
imageUrl: widget.articleEntity.articleImageUrl),
),
AppSize.sizeVer(10),
// Title
Text(
widget.articleEntity.title!.length > 63
? "${widget.articleEntity.title!.substring(0, 63)}..."
: widget.articleEntity.title!,
style: AppTextStyle.kTitleTextStyle
.copyWith(fontSize: 19),
),
],
),
),
),
),
AppSize.sizeVer(10),
// User Tag
// [BottomSection]: Include Usertag, like button, total like.
Row(
children: [
// [Container]: User tag
Container(
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(20.0),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 7.0,
vertical: 3.0,
),
child: FittedBox(
child: Row(
children: [
SizedBox(
width: 25,
height: 25,
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: profileWidget(
imageUrl:
widget.articleEntity.userProfileUrl),
),
),
AppSize.sizeHor(8),
Text(
widget.articleEntity.username!,
style: AppTextStyle.kTitleTextStyle.copyWith(
fontSize: 15,
color: Colors.white,
),
)
],
),
),
),
),
const Spacer(),
// [Text]: Total Likes.
Text(
'${widget.articleEntity.totalLikes} likes',
style: TextStyle(
color: AppColor.primaryColor,
fontWeight: FontWeight.bold,
),
),
AppSize.sizeHor(5),
// [Button]: Like Button.
InkWell(
onTap: _likeArticle,
child: Icon(
widget.articleEntity.likes!.contains(_currentUid)
? Icons.favorite
: Icons.favorite_outline,
color: widget.articleEntity.likes!.contains(_currentUid)
? Colors.red
: AppColor.primaryColor,
),
)
],
),
AppSize.sizeVer(10),
],
),
),
),
);
}
void _likeArticle() {
BlocProvider.of<ArticleCubit>(context).likeArticle(
articleEntity: ArticleEntity(
articleId: widget.articleEntity.articleId,
),
);
}
}
for ArticleCubit.getArticles.<anonymous closure>
this line reffer to emit(ArticleLoaded(articles: articles));
. This my problem from Debug Console:
E/flutter (14310): #0 BlocBase.emit
E/flutter (14310): #1 ArticleCubit.getArticles.<anonymous closure>
E/flutter (14310): #2 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
E/flutter ( 7916): #3 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter ( 7916): #4 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter ( 7916): #5 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter ( 7916): #6 _MapStream._handleData (dart:async/stream_pipe.dart:218:10)
E/flutter ( 7916): #7 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter ( 7916): #8 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
E/flutter ( 7916): #9 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter ( 7916): #10 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter ( 7916): #11 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter ( 7916): #12 _MapStream._handleData (dart:async/stream_pipe.dart:218:10)
E/flutter ( 7916): #13 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter ( 7916): #14 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
E/flutter ( 7916): #15 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter ( 7916): #16 _DelayedData.perform (dart:async/stream_impl.dart:515:14)
E/flutter ( 7916): #17 _PendingEvents.handleNext (dart:async/stream_impl.dart:620:11)
E/flutter ( 7916): #18 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:591:7)
E/flutter ( 7916): #19 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 7916): #20 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
NOTE: I can still do likes even though there are Unhandled Exception and im using firebase as database.