text
stringlengths
1
372
_highlight state internally. this example has two state
objects, _ParentWidgetState and _TapboxCState.
the _ParentWidgetState object:
the _TapboxCState object:
<code_start>
import 'package:flutter/material.dart';
//---------------------------- ParentWidget ----------------------------
class ParentWidget extends StatefulWidget {
const ParentWidget({super.key});
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
widget build(BuildContext context) {
return SizedBox(
child: TapboxC(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
//----------------------------- TapboxC ------------------------------
class TapboxC extends StatefulWidget {
const TapboxC({
super.key,
this.active = false,
required this.onChanged,
});
final bool active;
final ValueChanged<bool> onChanged;
@override
State<TapboxC> createState() => _TapboxCState();
}
class _TapboxCState extends State<TapboxC> {
bool _highlight = false;
void _handleTapDown(TapDownDetails details) {
setState(() {
_highlight = true;
});
}
void _handleTapUp(TapUpDetails details) {
setState(() {
_highlight = false;
});
}
void _handleTapCancel() {
setState(() {
_highlight = false;
});
}
void _handleTap() {
widget.onChanged(!widget.active);
}
@override
widget build(BuildContext context) {
// this example adds a green border on tap down.
// on tap up, the square changes to the opposite state.
return GestureDetector(
onTapDown: _handleTapDown, // handle the tap events in the order that
onTapUp: _handleTapUp, // they occur: down, up, tap, cancel
onTap: _handleTap,
onTapCancel: _handleTapCancel,
child: container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: widget.active ? Colors.lightGreen[700] : colors.grey[600],
border: _highlight
? border.all(
color: colors.teal[700]!,
width: 10,
)
: null,
),
child: center(
child: text(widget.active ? 'active' : 'inactive',
style: const TextStyle(fontSize: 32, color: colors.white)),
),
),
);
}
}
<code_end>
an alternate implementation might have exported the highlight
state to the parent while keeping the active state internal,
but if you asked someone to use that tap box,
they’d probably complain that it doesn’t make much sense.
the developer cares whether the box is active.
the developer probably doesn’t care how the highlighting
is managed, and prefers that the tap box handles those
details.
<topic_end>