dependencies:
provider:
import 'package:dart_printf/dart_printf.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Counter with ChangeNotifier {
Counter() {
printf('init');
}
int _n = 0;
int get n => _n;
set n(v) {
_n = v;
notifyListeners();
}
}
void main() {
var _app = MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
// var counter = Counter();
// ChangeNotifierProvider.value(value: counter),
],
child: MyApp(),
);
runApp(_app);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: Column(
children: [
Center(
child: Text('home page ${context.watch<Counter>().n}'),
),
W1(),
W2(),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
context.read<Counter>().n++;
},
),
);
}
}
class W1 extends StatefulWidget {
@override
_W1State createState() => _W1State();
}
class _W1State extends State<W1> {
@override
Widget build(BuildContext context) {
return Container(
100,
height: 100,
child: Text(context.watch<Counter>().n.toString()),
);
}
}
class W2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
100,
height: 100,
child: Text(context.watch<Counter>().n.toString()),
);
}
}