I have CounterProvider mixin with ChangeNotifier and inside the class i have two counters (_counterOne and _counterTwo) when _counterOne is inremented all Consumers are executed hence Widgets that consume _counterOne and _counterTwo are executed. But I want only the _counterOne consumer widget to execute.
I couldn't found any salution to do that.
Thanks in advance.
Provider:
class CounterProvider with ChangeNotifier {
int _counterOne = 1;
int getCounterOne() => _counterOne;
void incrementCounterOne() {
_counterOne++;
notifyListeners();
}
int _counterTwo = 2;
int getCounterTwo() => _counterTwo;
void incrementCounterTwo() {
_counterTwo++;
notifyListeners();
}
}
View:
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
#override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
late CounterProvider _provider;
#override
void initState() {
_provider = Provider.of<CounterProvider>(context, listen: false);
super.initState();
}
#override
Widget build(BuildContext context) => Scaffold(
body: Column(
children: [
Consumer<CounterProvider>(builder: (context, value, child) {
print("Consumer of CounterOne executed");
return Text("CounterOne: ${value.getCounterOne()}");
}),
Consumer<CounterProvider>(builder: (context, value, child) {
print("Consumer of CounterTwo executed");
return Text("CounterTwo: ${value.getCounterTwo()}");
}),
// Buttons
ElevatedButton(
onPressed: () {
_provider.incrementCounterOne();
},
child: const Text("Increment CounterOne"),
),
ElevatedButton(
onPressed: () {
_provider.incrementCounterTwo();
},
child: const Text("Increment CounterTwo"),
),
],
));
}
according to how Provider works if you use Consumer on a Provider class it will listen to any changes on that class and update every time there is change, To solve this you can use Selector as explained in here.
But ValueListenableBuilder also works fine as suggested in the comments.
Related
I'm trying to navigate to another page using blocs / cubits. I have one cubit that successfully navigates to another page upon completion of a method, but for some reason, it doesn't work on another cubit, despite successful state change, and operation done on the method.
class WalletCreateDialog extends StatefulWidget {
const WalletCreateDialog({required this.mnemonic});
final String mnemonic;
#override
_WalletCreateDialogState createState() => _WalletCreateDialogState();
}
class _WalletCreateDialogState extends State<WalletCreateDialog> {
#override
void initState() {
BlocProvider.of<WalletCreateCubit>(context)
.addCreatedWalletToWalletList(widget.mnemonic);
super.initState();
}
#override
Widget build(BuildContext context) {
return BlocListener<WalletCreateCubit, WalletCreateState>(
listener: (context, state) {
if (state is WalletAdded) {
Navigator.of(context).pop();
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
content: Text(
'Wallet added! Navigating back to home screen...',
),
),
);
Navigator.of(context).pushNamedAndRemoveUntil(
WalletOverviewHomeScreen.routeName,
(route) => false,
);
}
},
child: AlertDialog(
content: Container(
height: MediaQuery.of(context).size.height * 0.08,
child: Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text("Adding wallet..."),
const LoadingIndicator(),
],
),
),
],
),
),
),
);
}
}
In the line of code above, it successfully navigates to WalletOverviewHomeScreen upon successful completion of the addCreatedWalletToWalletList method.
class WalletDeleteDialog extends StatefulWidget {
const WalletDeleteDialog({required this.walletAddress});
final String walletAddress;
#override
State<WalletDeleteDialog> createState() => _WalletDeleteDialogState();
}
class _WalletDeleteDialogState extends State<WalletDeleteDialog> {
#override
void initState() {
BlocProvider.of<WalletDeleteCubit>(context)
.deleteWallet(widget.walletAddress);
super.initState();
}
#override
Widget build(BuildContext context) {
return BlocListener<WalletDeleteCubit, WalletDeleteState>(
listener: (context, state) {
if (state is WalletDeleteFinished) {
Navigator.of(context).pop();
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
content: Text(
'Wallet deleted! Navigating back to home screen...',
),
),
);
Navigator.of(context).pushNamedAndRemoveUntil(
WalletOverviewHomeScreen.routeName,
(route) => false,
);
}
},
child: AlertDialog(
content: Container(
height: MediaQuery.of(context).size.height * 0.08,
child: Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text("Deleting wallet..."),
const LoadingIndicator(),
],
),
),
],
),
),
),
);
}
}
On the other hand, in the line of code above, it doesn't navigate to the same screen after completion of the method. I've already verified that the state has changed in both cubits. Additionally, hot restarting the app would actually show that what was supposed to get deleted, did actually get deleted, thus there's no issue with regards to the implementation of the deleteWallet method itself.
How can I navigate to the WalletOverviewHomeScreen after completion of the deleteWallet method?
For context, below are the state classes for the Cubits.
part of 'wallet_create_cubit.dart';
abstract class WalletCreateState extends Equatable {
const WalletCreateState();
#override
List<Object> get props => [];
}
class WalletCreateInitial extends WalletCreateState {
const WalletCreateInitial();
#override
List<Object> get props => [];
}
class WalletCreateLoading extends WalletCreateState {
const WalletCreateLoading();
#override
List<Object> get props => [];
}
class WalletCreated extends WalletCreateState {
final String mnemonic;
const WalletCreated({required this.mnemonic});
#override
List<Object> get props => [mnemonic];
}
class WalletAdding extends WalletCreateState {
const WalletAdding();
#override
List<Object> get props => [];
}
class WalletAdded extends WalletCreateState {
const WalletAdded();
#override
List<Object> get props => [];
}
part of 'wallet_delete_cubit.dart';
abstract class WalletDeleteState extends Equatable {
const WalletDeleteState();
#override
List<Object> get props => [];
}
class WalletDeleteInitial extends WalletDeleteState {
const WalletDeleteInitial();
#override
List<Object> get props => [];
}
class WalletDeleteOngoing extends WalletDeleteState {
const WalletDeleteOngoing();
#override
List<Object> get props => [];
}
class WalletDeleteFinished extends WalletDeleteState {
const WalletDeleteFinished();
#override
List<Object> get props => [];
}
remove Navigator.of(context).pop();
because you don't need it. when you use Navigator.of(context).pushNamedAndRemoveUntil
Looks like the fix was to directly copy the contents of deleteFromWallet to the deleteWallet function. That is, in the WalletDeleteCubit it went from this:
Future<void> deleteWallet(String address) async {
FlutterSecureStorage storage = FlutterSecureStorage();
emit(WalletDeleteOngoing());
deleteFromWallet(storage, address);
debugPrint("Wallet with address: $address is deleted");
emit(WalletDeleteFinished());
debugPrint('Emit WalletDeleteFinished');
}
To this:
void deleteWallet(String address) async {
FlutterSecureStorage storage = FlutterSecureStorage();
emit(WalletDeleteOngoing());
await storage.delete(
key: WalletOverviewHomeScreen.walletKey + address,
);
debugPrint("Wallet with address: $address is deleted");
emit(WalletDeleteFinished());
debugPrint('Emit WalletDeleteFinished');
}
The minimal reproducible code below aims to have a loading icon when a button is pressed(to simulate loading when asynchronous computation happen).
For some reason, the Consumer Provider doesn't rebuild the widget when during the callback.
My view:
class HomeView extends StatefulWidget {
const HomeView();
#override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ChangeNotifierProvider(
create: (_) => HomeViewModel(99),
child: Consumer<HomeViewModel>(
builder: (_, myModel, __) => Center(
child: ButtonsAtBottom(
addEventAction: () => myModel.increment(context),
busy: myModel.busy
),
),
),
),
);
}
}
My model where I simulate to do business logic:
class HomeViewModel extends LoadableModel {
late int integer;
HomeViewModel(this.integer);
void increment(BuildContext context) {
super.setBusy(true);
Future.delayed(Duration(seconds: 3), () => print(integer++));
super.setBusy(false);
//Passed in context just to try to simulate my real app
//print(context);
}
}
class LoadableModel extends ChangeNotifier {
bool _busy = false;
bool get busy => _busy;
void setBusy(bool value) {
_busy = value;
notifyListeners();
}
}
PROBLEM: When the callback executes, and setBusy() methods within it are executed, they should notify the listeners and update the busy field passed in it. Subsequently, either a text or loader should be displayed.
BUT, busy field is never updated and remains as false.
class ButtonsAtBottom extends StatelessWidget {
final bool busy;
final void Function() addEventAction;
const ButtonsAtBottom({required this.busy, required this.addEventAction});
#override
Widget build(BuildContext context) {
print("busy value: $busy");
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () => Navigator.pop(context),
icon: Icon(Icons.clear_rounded),
),
ElevatedButton.icon(
onPressed: addEventAction,
icon: Icon(Icons.save_alt_rounded),
label: busy
? CircularProgressIndicator.adaptive(
backgroundColor: Colors.white,
)
: Text("Save")),
],
);
}
}
did you try to await the future?
I develop an app using BLoC pattern.
In my app there are 2 routes, route A and B, and both of them access same data.
A problem caused when moving the routes as below.
Move to route B from route A that shows the data.
Update the data at route B.
Back to route A.
After moving back to route A, the StreamBuilder of showing the data never updates automatically.
How can I let the StreamBuilder update on resumed state?
Here are sample codes.
routeA.dart
class RouteA extends StatefulWidget {
#override
_RouteAState createState() => _RouteAState();
}
class _RouteAState extends State<RouteA> {
#override
Widget build(BuildContext context) {
final bloc = Bloc();
return Column(
children: [
StreamBuilder( // this StreamBuilder never updates on resumed state
stream: bloc.data, // mistake, fixed. before: bloc.count
builder: (_, snapshot) => Text(
snapshot.data ?? "",
)),
RaisedButton(
child: Text("Move to route B"),
onPressed: () {
Navigator.of(context).pushNamed("routeB");
},
),
],
);
}
}
routeB.dart
class RouteB extends StatefulWidget {
#override
_RouteBState createState() => _RouteBState();
}
class _RouteBState extends State<RouteB> {
#override
Widget build(BuildContext context) {
final bloc = Bloc();
return Center(
child: RaisedButton(
child: Text("Update data"),
onPressed: () {
bloc.update.add(null);
},
),
);
}
}
bloc.dart
class Bloc {
Stream<String> data;
Sink<void> update;
Model _model;
Bloc() {
_model = Model();
final update = PublishSubject<void>();
this.update = update;
final data = BehaviorSubject<String>(seedValue: "");
this.data = data;
update.map((event) => _model.update()).listen((event) => data.sink.add(_model.getData()));
}
}
model.dart
class Model {
static Model _model;
factory Model() { // model is singleton.
_model ??= Model._();
return _model;
}
Model._();
int _data = 0;
void update() {
_data++;
}
String getData() {
return _data.toString();
}
}
StreamBuilder updates the data whenever it gets changed not when just by calling stream
RouteA
class RouteA extends StatefulWidget {
#override
_RouteAState createState() => _RouteAState();
}
class _RouteAState extends State<RouteA> {
#override
Widget build(BuildContext context) {
return Column(
children: [
StreamBuilder( // this StreamBuilder never updates on resumed state
stream: bloc.data, // mistake, fixed. before: bloc.count
builder: (_, snapshot) => Text(
snapshot.data ?? "",
)),
RaisedButton(
child: Text("Move to route B"),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (ctx) {
return RouteB();
}));
},
),
],
);
}
}
Route B
class RouteB extends StatefulWidget {
#override
_RouteBState createState() => _RouteBState();
}
class _RouteBState extends State<RouteB> {
#override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text("Update data"),
onPressed: () {
bloc.updateData();
},
),
);
}
}
Bloc
class Bloc {
final _update = PublishSubject<String>();
Model _model = Model();
Stream<String> get data => _update.stream;
void updateData() async {
_model.update();
_update.sink.add(_model.getData());
_update.stream.listen((event) {
print(event);
});
}
dispose() {
_update.close();
}
}
final bloc = Bloc();
just follow above changes, it will do the trick for you.
I'm trying to find the best way to show errors from a Change Notifier Model with Provider through a Snackbar.
Is there any built-in way or any advice you could help me with?
I found this way that is working but I don't know if it's correct.
Suppose I have a simple Page where I want to display a list of objects and a Model where I retrieve those objects from api. In case of error I notify an error String and I would like to display that error with a SnackBar.
page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Page extends StatefulWidget {
Page({Key key}) : super(key: key);
#override
_PageState createState() => _PageState();
}
class _PageState extends State< Page > {
#override
void initState(){
super.initState();
Provider.of<Model>(context, listen: false).load();
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
Provider.of< Model >(context, listen: false).addListener(_listenForErrors);
}
#override
Widget build(BuildContext context){
super.build(context);
return Scaffold(
appBar: AppBar(),
body: Consumer<Model>(
builder: (context, model, child){
if(model.elements != null){
...list
}
else return LoadingWidget();
}
)
)
);
}
void _listenForErrors(){
final error = Provider.of<Model>(context, listen: false).error;
if (error != null) {
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
backgroundColor: Colors.red[600],
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.error),
Expanded(child: Padding( padding:EdgeInsets.only(left:16), child:Text(error) )),
],
),
),
);
}
}
#override
void dispose() {
Provider.of<PushNotificationModel>(context, listen: false).removeListener(_listenForErrors);
super.dispose();
}
}
page_model.dart
import 'package:flutter/foundation.dart';
class BrickModel extends ChangeNotifier {
List<String> _elements;
List<String> get elements => _elements;
String _error;
String get error => _error;
Future<void> load() async {
try{
final elements = await someApiCall();
_elements = [..._elements, ...elements];
}
catch(e) {
_error = e.toString();
}
finally {
notifyListeners();
}
}
}
Thank you
Edit 2022
I ported (and reworked) this package also for river pod if anyone is interested
https://pub.dev/packages/riverpod_messages/versions/1.0.0
EDIT 2020-06-05
I developed a slightly better approach to afford this kink of situations.
It can be found at This repo on github so you can see the implementation there, or use this package putting in your pubspec.yaml
provider_utilities:
git:
url: https://github.com/quantosapplications/flutter_provider_utilities.git
So when you need to present messages to the view you can:
extend your ChangeNotifier with MessageNotifierMixin that gives your ChangeNotifier two properties, error and info, and two methods, notifyError() and notifyInfo().
Wrap your Scaffold with a MessageListener that will present a Snackbar when it gets called notifyError() or NotifyInfo()
I'll give you an example:
ChangeNotifier
import 'package:flutter/material.dart';
import 'package:provider_utilities/provider_utilities.dart';
class MyNotifier extends ChangeNotifier with MessageNotifierMixin {
List<String> _properties = [];
List<String> get properties => _properties;
Future<void> load() async {
try {
/// Do some network calls or something else
await Future.delayed(Duration(seconds: 1), (){
_properties = ["Item 1", "Item 2", "Item 3"];
notifyInfo('Successfully called load() method');
});
}
catch(e) {
notifyError('Error calling load() method');
}
}
}
View
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_utilities/provider_utilities.dart';
import 'notifier.dart';
class View extends StatefulWidget {
View({Key key}) : super(key: key);
#override
_ViewState createState() => _ViewState();
}
class _ViewState extends State<View> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: MessageListener<MyNotifier>(
child: Selector<MyNotifier, List<String>>(
selector: (ctx, model) => model.properties,
builder: (ctx, properties, child) => ListView.builder(
itemCount: properties.length,
itemBuilder: (ctx, index) => ListTile(
title: Text(properties[index])
),
),
)
)
);
}
}
OLD ANSWER
thank you.
Maybe I found a simpler way to handle this, using the powerful property "child" of Consumer.
With a custom stateless widget (I called it ErrorListener but it can be changed :))
class ErrorListener<T extends ErrorNotifierMixin> extends StatelessWidget {
final Widget child;
const ErrorListener({Key key, #required this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return Consumer<T>(
builder: (context, model, child){
//here we listen for errors
if (model.error != null) {
WidgetsBinding.instance.addPostFrameCallback((_){
_handleError(context, model); });
}
// here we return child!
return child;
},
child: child
);
}
// this method will be called anytime an error occurs
// it shows a snackbar but it could do anything you want
void _handleError(BuildContext context, T model) {
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
backgroundColor: Colors.red[600],
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.error),
Expanded(child: Padding( padding:EdgeInsets.only(left:16), child:Text(model.error) )),
],
),
),
);
// this will clear the error on model because it has been handled
model.clearError();
}
}
This widget must be put under a scaffold if you want to use a snackbar.
I use a mixin here to be sure that model has a error property and a clarError() method.
mixin ErrorNotifierMixin on ChangeNotifier {
String _error;
String get error => _error;
void notifyError(dynamic error) {
_error = error.toString();
notifyListeners();
}
void clearError() {
_error = null;
}
}
So for example we can use this way
class _PageState extends State<Page> {
// ...
#override
Widget build(BuildContext context) =>
ChangeNotifierProvider(
builder: (context) => MyModel(),
child: Scaffold(
body: ErrorListener<MyModel>(
child: MyBody()
)
)
);
}
You can create a custom StatelessWidget to launch the snackbar when the view model changes. For example:
class SnackBarLauncher extends StatelessWidget {
final String error;
const SnackBarLauncher(
{Key key, #required this.error})
: super(key: key);
#override
Widget build(BuildContext context) {
if (error != null) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => _displaySnackBar(context, error: error));
}
// Placeholder container widget
return Container();
}
void _displaySnackBar(BuildContext context, {#required String error}) {
final snackBar = SnackBar(content: Text(error));
Scaffold.of(context).hideCurrentSnackBar();
Scaffold.of(context).showSnackBar(snackBar);
}
}
We can only display the snackbar once all widgets are built, that's why we have the WidgetsBinding.instance.addPostFrameCallback() call above.
Now we can add SnackBarLauncher to our screen:
class SomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Title',
),
),
body: Stack(
children: [
// Other widgets here...
Consumer<EmailLoginScreenModel>(
builder: (context, model, child) =>
SnackBarLauncher(error: model.error),
),
],
),
);
}
}
i'm trying to pull new data from firebase cloud firestore and rebuild the widget on onPress of floating action button. i'm not sure how to rebuild the whole widget. Tried to call getList from the onPressed and setState() but still not rebulding widget evening nameList was updated.
class MyList extends StatefulWidget {
static const String id = 'test';
#override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('TEST'),),
body: MainList(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
backgroundColor: Colors.teal,
onPressed: () {
}),
);
}
}
class MainList extends StatefulWidget {
#override
_MainListState createState() => _MainListState();
}
class _MainListState extends State<MainList> {
List<Test> nameList = [];
#override
void initState() {
super.initState();
getList();
}
getList() async {
final _name = await
Firestore.instance.collection('test').getDocuments();
nameList.clear();
for (var name in _name.documents) {
Test addName = new Test(
name.data['name'],
);
nameList.add(addName);
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: nameList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Text(nameList[index].name),
);
});
}
}
Once a widget is created initState isn't called again. So your listview is still reflecting the old data.
You could getList in the onPressed which would then update your nameList. You could then pass this nameList to MainList.
class MyList extends StatefulWidget {
static const String id = 'test';
#override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
List<Test> nameList = [];
getList() async {
final _name = await
Firestore.instance.collection('test').getDocuments();
nameList.clear();
for (var name in _name.documents) {
Test addName = new Test(
name.data['name'],
);
nameList.add(addName);
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('TEST'),),
body: MainList(nameList: nameList),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
backgroundColor: Colors.teal,
onPressed: () {
getList();
}),
);
}
}
Your MainList widget would then look like:
class MainList extends StatefulWidget {
final List nameList;
MainList({this.nameList});
#override
_MainListState createState() => _MainListState();
}
class _MainListState extends State<MainList> {
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: nameList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Text(nameList[index].name),
);
});
}
}
Just calling setState() is not enough. You'll have to tell Dart what you are going to set. Sample code :
setState ( ()=> nameList = _fetchedList ) ;
In the above code, the variable nameList is assigned within setState().
In your code, you've two options.
Option 1 :
setState(() {
nameList.clear();
for (var name in _name.documents) {
Test addName = new Test(
name.data['name'],
);
nameList.add(addName);
}
});
Or option 2, better way, use for loop to add in the data in another list and use setState with one line as below :
List<Test> _fetchedList ;
for (var name in _name.documents) {
Test addName = new Test(
name.data['name'],
);
_fetchedList.add(addName);
}
setState( ()=> nameList = _fetchedList ) ;