Minimum reproducible code:
StreamController<int> _controller = StreamController();
Stream<int> _fooStream() => _controller.stream;
void main() {
runApp(
StreamProvider<int>(
initialData: 0,
lazy: false,
create: (_) => _fooStream(),
child: MaterialApp(
home: FooPage(),
),
),
);
}
class FooPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
child: Text('Get'),
onPressed: () {
_controller.add(1); // Added 1 but below line prints initial value
var value = context.read<int>(); // Prints 0
},
),
),
);
}
}
The question is, why the value prints 0 instead of 1. How should I read this value properly if it is already not the right way.
Note: I am not looking for workaround like adding Future.delayed(Duration.zero) before retrieving that value or listening for entire StreamProvider by doing context.watch<int>() in the build() method.