How to achieve showing snackbar without losing bloc state?
Suppose i have this widget class
Scaffold(
body: LoadingOverlay(
child: Container(
child: BlocConsumer<PostingBloc, PostingState>(
bloc: newBloc,
listener: (context, state) async {
if (state is PostingSuccess) {
//Show Snackbar
}
builder : (context, state){return Container(child:Text(state.text))}
}
then the bloc state is like this
class PostingState extends Equatable{
String text;
}
class PostingSuccess extends JobPostingState{
}
and the bloc mapEventToState is like this
PostingStateget initialState => PostingState();
Stream<PostingState> mapEventToState(
PostingEvent event,
) async* {
if (event is SuccessPost) {
yield PostingSuccess();
yield state;
}
Is it the correct way to implement snackbar on the bloc state management do i really need to yield twice to make the text still shown without the need to adding new variable like boolean showSuccess etc on my PostingState class.
Or is it the wrong way since there will be a time when the text is gone which is when the Posting Success emitted? I am quite confused on how to do this on bloc, any suggestion is really appreciated. thankyou
You can add your String inside your event and your state. After that:
if (event is SuccessPost) {
yield PostingSuccess(text: event.text);
}
Related
I have a screen(A) which use 'AccountFetched' state to load list of data from database:
return BlocProvider<AccountBloc>(
create: (context) {
return _accountBloc..add(FetchAccountEvent());
},
child: BlocBuilder<AccountBloc, AccountState>(
builder: (context, state) {
if (state is AccountFetched) {
accounts = state.accounts;
}
And in my second screen(B) I call AddAccountEvent to add data to database and navigate back to screen(A) which is the parent screen.
onPressed: () {
BlocProvider.of<AccountBloc>(context)
..add(AddAccountEvent(account: account));
Navigator.of(context).pop();
}
But when I navigate back to screen A, the list of data is not updated.
Should I refresh the screen(A) manually or how can I update the state of bloc?
This is my bloc class:
class AccountBloc extends Bloc<AccountEvent, AccountState> {
AccountBloc() : super(AccountInitial());
#override
Stream<AccountState> mapEventToState(AccountEvent event) async* {
if (event is FetchAccountEvent) yield* _fetchAccountEvent(event, state);
if (event is AddAccountEvent) yield* _addAccountEvent(event, state);
}
Stream<AccountState> _fetchAccountEvent(
FetchAccountEvent event, AccountState state) async* {
yield FetchingAccount();
final dbAccount = await DBAccountRepository.instance;
List<Account> accounts = await dbAccount.accounts();
yield AccountFetched(accounts: accounts);
}
Stream<AccountState> _addAccountEvent(
AddAccountEvent event, AccountState state) async* {
yield AddingAccount();
final dbAccount = await DBAccountRepository.instance;
final insertedId = await dbAccount.insertAccount(event.account);
yield AccountAdded(insertedId: insertedId);
}
}
I was experiencing the same problem, the solution I found was to make screen A wait for screen B to close, and after that trigger the data reload event for screen A.
onTap: () async {
await Navigator.of(context).push(ScreenB());
_bloc.add(RequestDataEvent());
}
So it will only execute the event after screen B is closed
well, you are creating a new bloc on page A. try to move BlocProvider 1 level up. so when the build function of page A calls, doesn't create a new bloc.
You should have a BlocListener in screen A listening for AccountState , with a if ( state is AccountFetched ) {} statement and perform your data update in a setState() . Depending on how long it takes to display screen A you might have the AccountFetched state been yielded before so screen A won't see it, in this case you could delay by 250 milliseconds yielding it in your _addAccount method either with a Timer or a Future.delayed.
Hope it helped.
I have a reuable stateful widget that returns a button layout. The button text changes to a loading spinner when the network call is in progress and back to text when network request is completed.
I can pass a parameter showSpinner from outside the widget, but that requires to call setState outside of the widget, what leads to rebuilding of other widgets.
So I need to call setState from inside the button widget.
I am also passing a callback as a parameter into the button widget. Is there any way to isolate the spinner change state setting to inside of such a widget, so that it still is reusable?
The simplest and most concise solution does not require an additional library. Just use a ValueNotifier and a ValueListenableBuilder. This will also allow you to make the reusable button widget stateless and only rebuild the button's child (loading indicator/text).
In the buttons' parent instantiate the isLoading ValueNotifier and pass to your button widget's constructor.
final isLoading = ValueNotifier(false);
Then in your button widget, use a ValueListenableBuilder.
// disable the button while waiting for the network request
onPressed: isLoading.value
? null
: () async {
// updating the state is super easy!!
isLoading.value = true;
// TODO: make network request here
isLoading.value = false;
},
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: isLoading,
builder: (context, value, child) {
if (value) {
return CircularProgressIndicator();
} else {
return Text('Load Data');
}
},
);
}
You can use StreamBuilder to solve this problem.
First, we need to create a stream. Create a new file to store it, we'll name it banana_stream.dart, for example ;).
class BananaStream{
final _streamController = StreamController<bool>();
Stream<bool> get stream => _streamController.stream;
void dispose(){
_streamController.close();
}
void add(bool isLoading){
_streamController.sink.add(isLoading);
}
}
To access this, you should use Provider, so add a Provider as parent of the Widget that contain your reusable button.
Provider<BananaStream>(
create: (context) => BananaStream(),
dispose: (context, bloc) => bloc.dispose(),
child: YourWidget(),
),
Then add the StreamBuilder to your button widget:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<bool>(
stream: Provider.of<BananaStream>(context, listen:false),
initialData: false,
builder: (context, snapshot){
final isLoading = snapshot.data;
if(isLoading == false){
return YourButtonWithNoSpinner();
} else{
return YourButtonWithSpinner();
}
}
);
}
}
And to change isLoading outside, you can use this code:
final provider = Provider.of<BananaStream>(context, listen:false);
provider.add(true); //here is where you change the isLoading value
That's it!
Alternatively, you can use ValueNotifier or ChangeNotifier but i find it hard to implement.
I found the perfect solution for this and it is using the bloc pattern. With this package https://pub.dev/packages/flutter_bloc
The idea is that you create a BLOC or a CUBIT class. Cubit is just a simplified version of BLOC. (BLOC = business logic component).
Then you use the bloc class with BlocBuilder that streams out a Widget depending on what input you pass into it. And that leads to rebuilding only the needed button widget and not the all tree.
simplified examples in the flutter counter app:
// input is done like this
onPressed: () {
context.read<CounterCubit>().decrement();
}
// the widget that builds a widget depending on input
_counterTextBuilder() {
return BlocBuilder<CounterCubit, CounterState>(
builder: (context, state) {
if (state.counterValue < 0){
return Text("negative value!",);
} else if (state.counterValue < 5){
return Text("OK: ${state.counterValue}",
);
} else {
return ElevatedButton(onPressed: (){}, child: const Text("RESET NOW!!!"));
}
},
);
}
UPDATE After finding the onChange override method it appears that the updated state is not being emitted #confused
UPDATE 2 Further debugging revealed that the StreamController appears to be closed when the updated state attempts to emit.
For some reason 1 of my BlocBuilders in my app refuses to redraw after a Cubit emit and for the life of me I cannot figure out why, there are no errors when running or debugging, the state data is being updated and passed into the emit.
Currently, it is a hook widget, but I have tried making it Stateless, Stateful, calling the cubit method in an effect, on context.bloc.
I have tried making it a consumer, nothing makes it into the listen, even tried messing with listenWhen and buildWhen and nothing is giving any indication as to why this is not building.
It renders the loading state and that is where it ends.
Widget:
class LandingView extends HookWidget {
#override
Widget build(BuildContext context) {
final hasError = useState<bool>(false);
return Scaffold(
key: const Key(LANDING_VIEW_KEY),
body: BlocProvider<CoreCubit>(
create: (_) => sl<CoreCubit>()..fetchDomainOptions(),
child: BlocBuilder<CoreCubit, CoreState>(
builder: (context, state) {
switch (state.status) {
case CoreStatus.loaded:
return LandingViewLoaded();
case CoreStatus.error:
return LandingViewError();
case CoreStatus.loading:
default:
return AppIcon();
}
},
),
),
);
}
}
Cubit method:
Future<void> fetchDomainOptions() async {
final inputEither = await getDomainOptions();
return inputEither.fold(
_handleFailure,
(options) {
emit(state.copyWith(
domainOptions: options,
status: CoreStatus.loaded,
));
},
);
}
I have a few other widgets that work off freezed data classes and work of the same status key logic without any issues, I even went as far as trying to add a lastUpdated timestamp key onto it to make even more data change, but in the initial state domainOptions is null and status is CoreStatus.loading, which should already be enough to trigger a UI update.
TIA
I haven't figured out yet why exactly this happens but I believe we're dealing with some kind of race condition here.
Also, I don't know the proper solution to work around that but I have found that delaying calling emit() for a short amount of time prevents this issue from occurring.
void load() async {
try {
emit(LoadingState());
final vats = await provider.all();
await Future<void>.delayed(const Duration(milliseconds: 50));
emit(LoadedState(vats));
} catch (e) {
print(e.toString());
emit(ErrorState());
}
}
Add await Future<void>.delayed(const Duration(milliseconds: [whatever is needed])); before emitting your new state.
I came to this conclusion after reading about this issue on cubit's GitHub: Emitted state not received by CubitBuilder
i resolved my problem, i was using getIt.
i aded the parameter bloc.
my problem was not recibing the events (emit) of the cubit (bloc)
child: BlocBuilder<CoreCubit, CoreState>(
bloc: getIt<CoreCubit>(), // <- this
builder: (context, state) {
},
),
I haven't found much about inter-bloc communication, so I came up with an own, simple solution that might be helpful to others.
My problem was: for one screen I use 2 blocs for different information clusters, one of them also re-used on another screen. While passing data is well documented, I had issues with figuring out how to pass events or trigger states to/of the other bloc.
There are probably much better solutions, but for other flutter or bloc beginners like me it might be helpful. It is fairly simple and the logic is easy to follow.
If you inject Bloc A as dependency to Bloc B (looked simple to me and I do not need further Blocs), I can get/set values in Bloc A from Bloc B (not vice versa). If I want to get data back to Bloc A, or if I just want the Bloc A build to reload, I can trigger events in the BlocBuilder of B to pass the information.
// ========= BLOC FILE ===========
class BlocA extends BlocAEvent, BlocAState> {
int myAVar = 1;
}
class BlocB extends BlocBEvent, BlocBState> {
BlocB({#required this.blocA}) : super(BInitial());
final BlockA blockA;
// passing data back and forth is straight forward
final myBVar = blockA.myAVar + 1;
blockA.myAVar = myBVar;
#override
Stream<BState> mapEventToState(BEvent event) async* {
if (event is BInitRequested) {
// trigger state change of Bloc B and request also reload of Bloc A with passed argument
yield LgSubjectShowSingle(blocAReloadTrigger: true);
}
}
}
// ========= UI FILE ===========
class MyPage extends StatelessWidget {
MyPage({Key key, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
// inject dependency of page on both Blocs: A & B
return MultiBlocProvider(
providers: [
BlocProvider<BlocA>(
create: (BuildContext context) =>
BlocA().add(BlocAInit()),
),
BlocProvider<BlocB>(
create: (BuildContext context) =>
BlocB(BlocA: BlocProvider.of<BlocA>(
context),).add(BInitRequested()),
),
],
child: BlocBuilder<BlocB, BState>(
builder: (context, state) {
if (state is BShowData) {
// If a reload of Bloc A is requested (we are building for Bloc B, here) this will trigger an event for state change of Bloc A
if (state.triggerStmntReload) {
BlocProvider.of<BlocA>(context).add(AReloadRequested());
};
return Text("abc");
}
}
)
);
}
}
I'm using flutter_bloc for state management and landed on this issue. When updating a field and saving it, the BlocBuilder is not refreshing the page. It is working fine when Adding or Deleting. I'm not sure what I'm doing wrong here.
Even if I go to a different screen and returning to this screen it still displays the old data even though the file was updated.
I spent more than 2 hours trying to debug this to no avail. I tried initializing the updatedTodos = [] then adding each todo one by one, to see if that does something, but that didn't work either.
Any help here would be appreciated.
TodosBloc.dart:
Stream<TodosState> _mapUpdateTodoToState(
TodosLoaded currentState,
UpdateTodo event,
) async* {
if (currentState is TodosLoaded) {
final index = currentState.Todos
.indexWhere((todo) => event.todo.id == todo.id);
final List<TodoModel> updatedTodos =
List.from(currentState.todos)
..removeAt(index)
..insert(index, event.todo);
yield TodosLoaded(updatedTodos);
_saveTodos(updatedTodos);
}
}
todos_screen.dart:
...
Widget build(BuildContext context) {
return BlocBuilder(
bloc: _todosBloc,
builder: (BuildContext context, TodosState state) {
List<TodoModel> todos = const [];
String _strings = "";
if (state is TodosLoaded) {
todos = state.todos;
}
return Expanded(
child: ListView.builder(
itemCount: todos.length,
itemBuilder: (BuildContext ctnx, int index) {
return Dismissible(
key: Key(todo.toString()),
child: DetailCard(
todo: todos[index],
),
);
},
),
);
...
I'm expecting when the BlocBuilder to be called and refreshed the ListView.
I was able to resolve this with the help of Felix Angelov on github.
The problem is that I'm extending Equatable but not passing the props to the super class in the TodoModel class. I had to update the constructor of the TodoModel with a super([]).
This is the way i solved the issue , even though it could not be the best solution but i'll share it , when you are on the other screen where you are supposed to show data or something , upon pressing back button call dispose as shown below
#override
void initState() {
super.initState();
print("id" + widget.teamID);
BlocProvider.of<FootBallCubit>(context).getCurrentTeamInfo(widget.teamID);
}
// what i noticed upon closing this instance of screen , it deletes old data
#override
void dispose() {
super.dispose();
Navigator.pop(context);
}