Flutter + Bloc 6.0.6. BlocBuilder's "builder" callback isn't provided with the same state as the "buildWhen" callback - flutter

I'm building a tic-tak-toe app and I decided to learn BLoC for Flutter along. I hava a problem with the BlocBuilder widget.
As I think about it. Every time Cubit/Bloc that the bloc builder widget listens to emits new state the bloc builder goes through this routine:
Call buildWhen callback passing previous state as the previous parameter and the newly emitted state as the current parameter.
If the buildWhen callback returned true then rebuild.
During rebuilding call the builder callback passing given context as context parameter and the newly emitted state as state parameter. This callback returns the widget that we return.
So the conclusion is that the current parameter of the buildWhen call is always equal to the state parameter of the builder call. But in practice it's different:
BlocBuilder<GameCubit, GameState>(
buildWhen: (previous, current) => current is SetSlotSignGameState && (current as SetSlotSignGameState).slotPosition == widget.pos,
builder: (context, state) {
var sign = (state as SetSlotSignGameState).sign;
// Widget creation goes here...
},
);
In the builder callback, it throws:
The following _CastError was thrown building BlocBuilder<GameCubit, GameState>(dirty, state:
_BlocBuilderBaseState<GameCubit, GameState>#dc100):
type 'GameState' is not a subtype of type 'SetSlotSignGameState' in type cast
The relevant error-causing widget was:
BlocBuilder<GameCubit, GameState>
The method where I emit the states that is in the GameCubit class:
// [pos] is the position of the slot clicked
void setSlotSign(Vec2<int> pos) {
// Some code
emit(SetSlotSignGameState(/* Parameter representing the sign that is being placed in the slot*/, pos));
// Some code
emit(TurnChangeGameState());
}
Briefly about types of states. SetSlotSignGameState is emitted when a user taps on a slot in the tic-tac-toe grid and the slot is empty. So this state means that we need to change sign in some slot. TurnChangeGameState is emitted when we need to give the turn to the next player.
Temporary solution. For now I fixed it by saving the state from buildWhen callback in a private field of the widget's state and then using it from the builder. BlocListener also has this problem but there I can just move the check from listenWhen callback into listen callback. The disadvantage of this solution is that it's very inelegant and inconvenient.

buildWhen is bypassed (not even called) on initial state OR when Flutter requests a rebuild.
I have created a small "test" to emphasize that:
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(BlocTestApp());
}
class BlocTestApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider<TestCubit>(
// Create the TestCubit and call test() event right away
create: (context) => TestCubit()..test(),
child: BlocBuilder<TestCubit, String>(
buildWhen: (previous, current) {
print("Call buildWhen(previous: $previous, current: $current)");
return false;
},
builder: (context, state) {
print("Build $state");
return Text(state);
},
),
),
);
}
}
class TestCubit extends Cubit<String> {
TestCubit() : super("Initial State");
void test() {
Future.delayed(Duration(seconds: 2), () {
emit("Test State");
});
}
}
OUTPUT:
I/flutter (13854): Build Initial State
I/flutter (13854): Call buildWhen(previous: Initial State, current: Test State)
As can be seen from output the initial state is built right away without calling buildWhen. Only when the state changes buildWhen is examined.
Other References
This behavior is also outlined here by the creator of Flutter Bloc library (#felangel):
This is expected behavior because there are two reasons for a
BlocBuilder to rebuild:
The bloc state changed
Flutter marked the widget as needing to be rebuilt.
buildWhen will prevent builds triggered by 1 but not by 2. In
this case, when the language changes, the whole widget tree is likely
being rebuilt which is why the BlocBuilder is rebuilt despite
buildWhen.
Possible solution
In your situation, based on the little code you revealed, is better to store the entire Tic-Tac-Toe configuration in the state and use BLOC events to alter it. In this way you do not need that buildWhen condition.
OR make the check inside the builder function if the logic let you do that (this is the most common used solutions with BLOC).
To respond to you question (if not clear so far :D): Sadly, you can not rely on buildWhen to filter the state types sent to builder function.

Could you please check if SetSlotSignGameState extends the abstract class GameState

Related

Flutter BlocProvider consumption

I'm implementing a BLoC pattern for state management in my Fluter application. As I'm new in Flutter and BLoC particularly I'm evolving its usage gradually.
For new I use BLoC to communicate between two pages. One page sends an asset to the BLoC and navigates to details page. The details page uses StreamBuilder to read from the BLoC and build page with according data:
AppWidget:
Widget build(BuildContext context) => MultiProvider(
providers: [
BlocProvider(create: (context) => AssetBloc())
...
Requesting page
_onAssetMenuAction(BuildContext context, AssetMenu value, Asset asset) {
switch (value) {
case AssetMenu.validate:
var bloc = BlocProvider.of<AssetBloc>(context);
bloc.validate(asset);
Navigator.push(context,
MaterialPageRoute(builder: (context) => ValidateAssetPage()));
break;
}
Validation page
Widget build(BuildContext context) {
var bloc = BlocProvider.of<AssetBloc>(context);
Logger.root.info("Building validation page");
return StreamBuilder<AssetValidation>(
stream: bloc.outValidation,
builder: (context, snapshot) => snapshot.hasData
? QrImage.withQr(qr: snapshot.data!.qr)
: Text("No QR"));
}
BLoC
class AssetBloc extends BlocBase {
//
// Stream to handle the validation request outcome
//
StreamController<AssetValidation> _validationController =
StreamController<AssetValidation>.broadcast();
StreamSink<AssetValidation> get _inValidation => _validationController.sink;
Stream<AssetValidation> get outValidation => _validationController.stream;
//
// Stream to handle the validation request
//
StreamController<Asset> _validateController = StreamController<Asset>();
void Function(Asset) get validate => _validateController.sink.add;
//
// Constructor
//
AssetBloc([state]) : super(state) {
_validateController.stream.listen(_handleLogic);
}
void _handleLogic(Asset asset) {
_inValidation.add(AssetValidation.create(asset));
Logger.root.finest("AssetValidation instance is sent to stream");
}
void dispose() {
_validateController.close();
_validationController.close();
}
}
The problem I have is I'm getting "No QR". According to logs I see following sequence of actions:
new AssetValidation.create(): Validating asset Instance of 'Asset'
AssetBloc._handleLogic(): AssetValidation instance is sent to stream
ValidateAssetPage.build(): Building validation page
So at the moment of validation page building the validation result data should be in the stream but it seems they are not.
Unit tests of AssetBloc work as expected. So I suspect it should be related to StreamBuilder in validation page.
The StreamBuilder just shows you the last value of the stream whether the StreamBuilder was present on the current deployed widget when the stream was updated. So, if you add a new value to the stream, but the StreamBuilder is not on the current deployed widget, and, after that, you deploy the widget with the StreamBuilder, it's very likely that it won't show the updated data (in fact it shows empty data). I know, it's weird, i have the same problem when i like to use streams in that way. So, instead, i recommend you to use ValueListenable on the bloc and ValueListenableBuilder on the widget. It's very useful for that cases.
Another thing to point out is that if you're going to use just streams for the state management, it's better to use another state manager type such as provider or singleton. The reason is that, the right way to use bloc (the way you take advantage of the power of bloc) is using just the method add() for the events and logic, and using the established bloc State classes to show and update the data with the BlocBuilder on the widget.

flutter bloc - dispatch event to hosting widget without changing the state

I got this situation:
screen1 (widget) navigates to screen2 (widget) and passes it a function (callback)
screen2 has its own bloc (bloc2)
screen2 add event to bloc2
bloc2 performs a long async operation
when operation completes, bloc2 should notify screen2 (The problem is here)
screen2 should invoke the passed function
screen1 in a réponse should close screen2
How should bloc2 notify screen2 without changing a state.
Changing the state seems a redundant operation in this case, as I don't see a point in build function to run again (and returning a redundant widget)
Assuming you are using a BlocBuilder to build screen2, then you could use the buildWhen property to determine on which conditions to rebuild, maybe never on state-change?
You can get the blocs public properties and methods using the previous and current parameters. Those parameters are of type BlocAState.
BlocBuilder<BlocA, BlocAState>(
buildWhen: (previous, current) {
// return true/false to determine whether or not
// to rebuild the widget with state
},
builder: (context, state) {
// return widget here based on BlocA's state
}
)
Furthermore, this step:
screen2 should invoke the passed function
Should, probably, be done in a BlocListener or BlocConsumer. Maybe that is already how you do it, if not. Look into it..
So to solve your problem I would imagine that you should switch your BlocBuilder to a BlocConsumer, actually change the state, because your "long async operation" does change the state of screen2 from "not done the long thing", to "has done the long thing". Then your BlocListener can invoke the passed function, and the buildWhen property can make sure to not rebuild your screen2.
The BlocConsumer looks like this:
BlocConsumer<BlocA, BlocAState>(
listenWhen: (previous, current) {
// return true/false to determine whether or not
// to invoke listener with state
},
listener: (context, state) {
// do stuff here based on BlocA's state
// I.e. invoke the passed function
},
buildWhen: (previous, current) {
// return true/false to determine whether or not
// to rebuild the widget with state
},
builder: (context, state) {
// return widget here based on BlocA's state
}
)

Flutter Riverpod: using ref.watch in the constructor for a ChangeNotifier, how to avoid Notifier being recreated upon changes

I have a ChangeNotifier, which I use with ChangeNotifierProvider to track the state of a screen in my app. It has a constructor:
CategoryViewState(ProviderRefBase ref, int listId) {
subjects = ref.watch(otherProvider.select((value) => value.getSubjects()));
}
The problem I'm encountering is that when otherProvider.getSubjects() changes, the whole ChangeNotifier is recreated from scratch, rather than the subjects list being updated. This means the state of the page is lost.
Is there a fix or another way to do this that avoids this happening?
Just put the widget that list to the changes in a Consumer widget and watch changes inside it:
Consumer(builder: (context, ref, child) {
final subjects = ref.watch(otherProvider.select((value) => value.getSubjects()));
return YourWidget(); // Just this widget will be rebuilt
},)

Flutter Navigator popUntil with Bloc not rebuilding state

I have a 3 step form, For each step I am pushing a new page by passing the Bloc provider wrapped in MaterialPageRoute using Navigator so the same bloc can be accessed on those pages like this:
Navigator.of(context).push(MaterialPageRoute<TeacherTemperature>(
builder: (_) => BlocProvider.value(value: BlocProvider.of<TeacherattendanceclassBloc>(context),
child: TeacherTemperature()))
);
Now on the last step, when the form is completed I am doing popUntil to go back to step 1 and update the state:
Navigator.popUntil(context, ModalRoute.withName("teacherAttendanceClassList"));
BlocProvider.of<TeacherattendanceclassBloc>(context)
.add(StudentsCheckedInCompleted(widget.studentList!.length));
This successfully goes back to step 1 page and also I am able to call the event StudentsCheckedInCompleted event and the bloc is processing the state change as well.
But The step one page is not re-building for some reason? (I have tried to but the condition under the BlocBuilder as well)
This is the step one page, where I'm listening for the state in the BlocListener like this:
BlocListener<TeacherattendanceclassBloc, TeacherattendanceclassState>(
listener: (context, state) {
print(state);
if(state is StudentSelectionUpdated){
childrenSelectedList = state.studentsSelectedList;
}
if(state is StudentsCheckedInSuccessfull){ ----> this is not being triggered on the page
print('StudentsCheckedInSuccessfully is triggered on the teacher attendance page');
}
},
Am I missing somethig?
This issue might be caused by State equatibility check, which means:
Assume this is your state;
class MyState extends Equatable {
final String myVariable1;
final int myVariable2;
MyState({this.myVariable, this.myVariable2});
#override
List<Object> get props => [myVariable, myVariable2];
}
on the bottom, as you see, there is props which helps bloc to decide if state is changed or altered, and if that prop say "i am changed" (by changing any content of it), bloc rebuilds the widget. But if your state is not altered/changed as intended or you forgot to add proper props that will later say to bloc that you edited your state, your widget will not be rebuilt.
Maybe you can can add more details in code to understand the root cause. (Can you please share your bloc, events and your state objects)

using didUpdateWidget to replace a stream causes "bad state: Stream has already been listened to"

I have a StreamBuilder that I want to be able to pause and unpause and, since StreamBuilder doesn't expose it's underlying StreamSubscription, I have to create a proxy stream to forward the source stream's elements while exposing a StreamSubscription that I can pause and unpause. This forces me to convert my stateless widget into a stateful widget so I have access to dispose and can close it's StreamController.
I'm following the didUpdateWidget documentation's instructions:
In initState, subscribe to the object.
In didUpdateWidget unsubscribe from the old object and subscribe to the new one if the updated widget configuration requires replacing the object.
In dispose, unsubscribe from the object.
I need to replace the Stream whenever the user types in a new search query. My stateful widget is re-constructed within a ChangeNotifier whenever a new stream is received.
Here's the relevant part of my stateful widget:
final Stream<List<Entry>> _entryStream;
StreamController<List<Entry>> _entryStreamController;
StreamSubscription<List<Entry>> _entryStreamSubscription;
_EntryListState(this._entryStream);
void initStream() {
_entryStreamController?.close();
_entryStreamController = StreamController();
_entryStreamSubscription = _entryStream.listen((event) {
_entryStreamController.add(event);
}
)..onDone(() => _entryStreamController.close());
}
#override
void initState() {
initStream();
super.initState();
}
#override
void dispose() {
_entryStreamController?.close();
super.dispose();
}
#override
void didUpdateWidget(EntryList oldEntryList) {
// Initialize the stream only if it has changed
if (oldEntryList._entryStream != _entryStream) initStream();
super.didUpdateWidget(oldEntryList);
}
This is the line throwing the BadState error:
_entryStreamSubscription = _entryStream.listen((event) {
_entryStreamController.add(event);
}
And here is where my widget is being constructed:
child: Consumer<SearchStringModel>(
builder: (context, searchStringModel, child) {
print('rebuilding with: ${searchStringModel.searchString}');
var entryStream = _getEntries(searchStringModel.searchString);
return EntryList(entryStream);
}
),
I don't think I understand didUpdateWidget in particular and suspect that's where the two issues (bad state, and not updating) are coming from? I'm also re-constructed the stateful widget instead of just modifying its state which is a little confusing, but the widget is intended to act as a stateless widget for all intents and purposes so it'd be a pain to update it to update state instead of reconstructing. Any advice?
I had not read the "didUpdateWidget" documentation closely enough. This is the key paragraph:
/// If the parent widget rebuilds and request that this location in the tree
/// update to display a new widget with the same [runtimeType] and
/// [Widget.key], the framework will update the [widget] property of this
/// [State] object to refer to the new widget and then call this method
/// with the previous widget as an argument.
In my consumer, I'm rebuilding with a new EntryList. As the above paragraph describes, the framework will then call didUpdateWidget on the same state object (as opposed to a new one). In order to check whether or not the configuration has changed and, if it has, to access the new configuration, I need to access the widget property of my state object. With this in mind, here is my new implementation of didUpdateWidget:
#override
void didUpdateWidget(EntryList oldEntryList) {
super.didUpdateWidget(oldEntryList);
// Initialize the stream only if it has changed
if (widget._entryStream != _entryStream) {
_entryStream = widget._entryStream;
initStream();
}
}
Note that I am now checking widet._entryStream and then setting the state's _entryStream to it if it's changed.
Hopefully someone else running into a similar problem will be helped by this!