Skip to content

Instantly share code, notes, and snippets.

@tomalabaster
Created November 28, 2023 18:58
Show Gist options
  • Save tomalabaster/c8644533f5fc85174380a9ce4734c8d0 to your computer and use it in GitHub Desktop.
Save tomalabaster/c8644533f5fc85174380a9ce4734c8d0 to your computer and use it in GitHub Desktop.
Counter example
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
super.key,
required this.title,
}) ;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
print("MyHomePage building");
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
// Try changing `count: _counter,` to `_count: 0` and
child: CounterValue(
count: _counter,
child: const CounterText(),
)
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class CounterValue extends InheritedWidget {
final int count;
const CounterValue({
super.key,
required super.child,
required this.count,
});
@override
bool updateShouldNotify(CounterValue oldWidget) => false;
// Change the updateShouldNotify method to the one commented out below to see the CountText update
// @override
// bool updateShouldNotify(CounterValue oldWidget) => count != oldWidget.count;
// Change the updateShouldNotify method to the one commented out below to always have the CountText build even if nothing changes (see comment above about always setting count to 0)
// @override
// bool updateShouldNotify(CounterValue oldWidget) => true;
}
class CounterText extends StatelessWidget {
const CounterText({super.key});
@override
Widget build(BuildContext context) {
print("CounterText building");
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'${context.dependOnInheritedWidgetOfExactType<CounterValue>()!.count}',
style: Theme.of(context).textTheme.headlineMedium,
),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment