Skip to content

Instantly share code, notes, and snippets.

@gazialankus
Last active July 3, 2021 20:52
Show Gist options
  • Save gazialankus/5afd0b023c9550709dc15892e4a69c38 to your computer and use it in GitHub Desktop.
Save gazialankus/5afd0b023c9550709dc15892e4a69c38 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
print('MyHomePage is rebuilt with $_counter');
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: CountValue(
value: _counter,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const FixedTextWidget(),
const DummyInBetweenWidget(),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class FixedTextWidget extends StatelessWidget {
const FixedTextWidget({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
print('FixedText is rebuilt');
return Text(
'You have pushed the button this many times:',
);
}
}
class CountDisplayWidget extends StatelessWidget {
const CountDisplayWidget({
Key? key
}) : super(key: key);
@override
Widget build(BuildContext context) {
int counter = CountValue.of(context).value;
print('CountDisplay is rebuilt with $counter');
return Text(
'$counter',
style: Theme.of(context).textTheme.headline4,
);
}
}
class CountValue extends InheritedWidget {
const CountValue({
Key? key,
required this.value,
required Widget child,
}) : super(key: key, child: child);
final int value;
static CountValue of(BuildContext context) {
final CountValue? result = context.dependOnInheritedWidgetOfExactType<CountValue>();
assert(result != null, 'No CountValue found in context');
return result!;
}
@override
bool updateShouldNotify(CountValue old) => value != old.value;
}
class DummyInBetweenWidget extends StatelessWidget {
const DummyInBetweenWidget({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
print('DummyInBetweenWidget is rebuilt');
return const CountDisplayWidget();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment