Skip to content

Instantly share code, notes, and snippets.

@s0nerik
Created October 25, 2023 12:26
Show Gist options
  • Save s0nerik/2ef7f5dc9fe1bda0be23ffd1b1dd23d5 to your computer and use it in GitHub Desktop.
Save s0nerik/2ef7f5dc9fe1bda0be23ffd1b1dd23d5 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';
import 'dart:async';
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({
Key? key,
required this.title,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: _State1(
child: _State2(),
),
);
}
}
class _State1 extends StatefulWidget {
const _State1({
super.key,
required this.child,
});
final Widget child;
@override
State<_State1> createState() => _State1State();
}
class _State1State extends State<_State1> {
var _builds = 0;
@override
void initState() {
super.initState();
Timer(const Duration(milliseconds: 1000), () {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
_builds++;
return Column(
children: [
Text('Parent builds: $_builds'),
widget.child,
// Uncomment each of these separately and see the difference
// _State2(),
// const _State2(),
],
);
}
}
class _State2 extends StatefulWidget {
const _State2({
super.key,
});
@override
State<_State2> createState() => _State2State();
}
class _State2State extends State<_State2> {
var _builds = 0;
@override
Widget build(BuildContext context) {
_builds++;
return Text('Child builds: $_builds');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment