Como minhas SnackBar estavam deixando o código muito repetitivo, fiz uma função a parte para elas:
01º Criei uma enum
na pasta models
para tipá-las e chamei de custom_snackbar_enum.dart
:
enum CustomSnackBarTypes {
success,
error
}
02º Criei o componente dentro da pasta widgets
, da home_screen
, chamado custom_snackbar.dart
:
import 'package:api_project/models/custom_snackbar_enum.dart';
import 'package:flutter/material.dart';
showCustomSnackBar({
required BuildContext context,
required CustomSnackBarTypes type,
required String content,
}) {
if (type == CustomSnackBarTypes.success) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(content),
const Icon(
Icons.done,
color: Colors.white,
)
],
),
backgroundColor: Colors.green,
duration: const Duration(milliseconds: 1500),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(content),
const Icon(
Icons.warning,
color: Colors.white,
)
],
),
backgroundColor: Colors.red,
duration: const Duration(milliseconds: 1500),
),
);
}
}
03º Por fim, chamei essa função showCustomSnackBar
nas funções callAddJournalScreen
e removeJournal
do journal_card.dart
:
callAddJournalScreen(BuildContext context, {Journal? journal}) {
Journal innerJournal = Journal(
id: const Uuid().v1(),
content: '',
createdAt: showedDate,
updatedAt: showedDate,
);
Map<String, dynamic> map = {};
if (journal != null) {
innerJournal = journal;
map['is_editing'] = true;
} else {
map['is_editing'] = false;
}
map['journal'] = innerJournal;
Navigator.pushNamed(
context,
'add-journal',
arguments: map,
).then((result) {
if (result != null && result == true) {
showCustomSnackBar(
context: context,
type: CustomSnackBarTypes.success,
content: 'Journal saved successfully...',
);
} else {
showCustomSnackBar(
context: context,
type: CustomSnackBarTypes.error,
content: 'Error on adding Journal...',
);
}
refreshFunction();
});
}
removeJournal(BuildContext context) {
if (journal != null) {
JournalService journalService = JournalService();
journalService.delete(journal!.id).then(
(value) {
if (value) {
showCustomSnackBar(
context: context,
type: CustomSnackBarTypes.success,
content: 'Journal removed successfully...',
);
refreshFunction();
} else {
showCustomSnackBar(
context: context,
type: CustomSnackBarTypes.error,
content: 'Error on removing Journal...',
);
}
},
);
}
}