Created
September 18, 2020 11:57
-
-
Save FantasyCheese/2f6993636d534d93d04fb52bc4d685cb to your computer and use it in GitHub Desktop.
Simplest MultiProvider Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
import 'package:provider/provider.dart'; | |
void main() { | |
runApp(MultiProvider( | |
providers: [ | |
ChangeNotifierProvider(create: (_) => Counter()), | |
ChangeNotifierProvider(create: (_) => Clock()) | |
], | |
child: MyApp(), | |
)); | |
} | |
class Counter extends ChangeNotifier { | |
Counter() { | |
Timer.periodic(Duration(seconds: 1), (timer) { | |
_count++; | |
notifyListeners(); | |
}); | |
} | |
int _count = 42; | |
int get count => _count; | |
} | |
class Clock extends ChangeNotifier { | |
Clock() { | |
Timer.periodic(Duration(seconds: 3), (timer) { | |
_dateTime = DateTime.now(); | |
notifyListeners(); | |
}); | |
} | |
DateTime _dateTime = DateTime.now(); | |
DateTime get dateTime => _dateTime; | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
final dateTime = context.watch<Clock>().dateTime; | |
final count = context.watch<Counter>().count; | |
return Center( | |
child: RichText( | |
text: TextSpan(text: "$dateTime\n$count"), | |
textDirection: TextDirection.ltr, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a great example. Thank you for this.