Skip to content

Instantly share code, notes, and snippets.

@FantasyCheese
Created September 18, 2020 11:57
Show Gist options
  • Save FantasyCheese/2f6993636d534d93d04fb52bc4d685cb to your computer and use it in GitHub Desktop.
Save FantasyCheese/2f6993636d534d93d04fb52bc4d685cb to your computer and use it in GitHub Desktop.
Simplest MultiProvider Example
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,
),
);
}
}
@nav9
Copy link

nav9 commented Sep 13, 2024

This is a great example. Thank you for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment