サンプルコードのウィジェットの階層構造
#
App
└ Layer1
└ Layer2
├ Layer3A
└ Layer3B
setState
#
import 'package:flutter/material.dart';
void main() => runApp(const App());
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Layer1());
}
}
class Layer1 extends StatefulWidget {
const Layer1({Key? key}) : super(key: key);
@override
State<Layer1> createState() => _Layer1State();
}
class _Layer1State extends State<Layer1> {
int _count = 0;
void _increment() => setState(() => _count++);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Current count is $_count')),
body: Layer2(count: _count, increment: _increment),
);
}
}
class Layer2 extends StatelessWidget {
const Layer2({Key? key, required this.count, required this.increment})
: super(key: key);
final int count;
final void Function() increment;
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('I am a counter.'),
Layer3A(count: count),
Layer3B(increment: increment),
],
);
}
}
class Layer3A extends StatelessWidget {
const Layer3A({Key? key, required this.count}) : super(key: key);
final int count;
@override
Widget build(BuildContext context) {
final String res = count % 2 == 0 ? 'Even' : 'Odd';
return Text('Count is $res');
}
}
class Layer3B extends StatelessWidget {
const Layer3B({Key? key, required this.increment}) : super(key: key);
final void Function() increment;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: increment,
child: const Text('INCREMENT'),
);
}
}
Prop Drilling(バケツリレー)になっています。
...