Skip to content

Instantly share code, notes, and snippets.

@davidmartos96
Created July 15, 2020 07:00
Show Gist options
  • Save davidmartos96/5bd829c1c43b124fb4c98f32267bfdb8 to your computer and use it in GitHub Desktop.
Save davidmartos96/5bd829c1c43b124fb4c98f32267bfdb8 to your computer and use it in GitHub Desktop.
Provider: markNeedsRebuild() called during build
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MultiProvider(
providers: [
ChangeNotifierProvider<ANotifier>(create: (context) => ANotifier()),
ChangeNotifierProxyProvider<ANotifier, BNotifier>(
create: (_) => BNotifier(),
update: (_, aNot, bNot) {
bNot.onANotifierUpdated(aNot);
return bNot;
},
)
],
child: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final bNotifier = Provider.of<BNotifier>(context);
print("BUILDING: ${DateTime.now()}");
return Scaffold(
appBar: AppBar(
title: Text(bNotifier.myValue),
),
body: Center(
child: FlatButton(
onPressed: () async {
final bNotifier = Provider.of<BNotifier>(context, listen: false);
final aNotifier = Provider.of<ANotifier>(context, listen: false);
await showModalBottomSheet<void>(
context: context,
builder: (context) {
// Inject the providers to use in the bottom sheet route
return MultiProvider(
providers: [
ChangeNotifierProvider<ANotifier>.value(value: aNotifier),
ChangeNotifierProvider<BNotifier>.value(value: bNotifier)
],
builder: (context, _) {
return MyBottomSheet();
},
);
},
);
},
child: Text("Open bottom sheet"),
color: Colors.blue,
),
),
);
}
}
class MyBottomSheet extends StatelessWidget {
const MyBottomSheet({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final bNotifier = Provider.of<BNotifier>(context);
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(bNotifier.myValue),
FlatButton(
onPressed: () {
final aNotifier = Provider.of<ANotifier>(context, listen: false);
aNotifier.update();
},
child: Text("Trigger error"),
color: Colors.blue,
),
],
);
}
}
class ANotifier extends ChangeNotifier {
void update() {
print("UPDATE A");
notifyListeners();
}
}
class BNotifier extends ChangeNotifier {
int _value = 0;
BNotifier();
void update() {
_value++;
notifyListeners();
}
String get myValue => "BNotifier State = $_value";
void onANotifierUpdated(ANotifier a) {
print("onANotifierUpdated...");
notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment