import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterPage(),
);
}
}
class CounterPage extends StatefulWidget {
@override
_CounterPageState createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('You have pushed the button this many times: $counter'),
),
floatingActionButton: FloatingActionButton(
onPressed: incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class CounterInheritedWidget extends InheritedWidget {
final int counter;
CounterInheritedWidget({
Key key,
@required this.counter,
@required Widget child,
}) : super(key: key, child: child);
static CounterInheritedWidget of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CounterInheritedWidget>();
}
@override
bool updateShouldNotify(CounterInheritedWidget oldWidget) {
return counter != oldWidget.counter;
}
}
class CounterText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
'You have pushed the button this many times: ${CounterInheritedWidget.of(context).counter}',
style: Theme.of(context).textTheme.headline4,
);
}
}
class CounterPageWithInheritedWidget extends StatefulWidget {
@override
_CounterPageWithInheritedWidgetState createState() => _CounterPageWithInheritedWidgetState();
}
class _CounterPageWithInheritedWidgetState extends State<CounterPageWithInheritedWidget> {
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return CounterInheritedWidget(
counter: counter,
child: Scaffold(
body: Center(
child: CounterText(),
),
floatingActionButton: FloatingActionButton(
onPressed: incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This t
评论已关闭