Skip to content

Instantly share code, notes, and snippets.

@RyouMon
Created November 6, 2022 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyouMon/dcb18445489fed89f16693e30508d36b to your computer and use it in GitHub Desktop.
Save RyouMon/dcb18445489fed89f16693e30508d36b to your computer and use it in GitHub Desktop.
Manager some states by self, other by parent
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Tap Box B',
home: ParentWidget(),
);
}
}
class ParentWidget extends StatefulWidget {
const ParentWidget({super.key});
@override
State<StatefulWidget> createState() {
return _ParentWidgetState();
}
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
@override
Widget build(BuildContext context) {
return Tapbox(
active: _active,
onChanged: _handleTapboxChanged,
);
}
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
}
class Tapbox extends StatefulWidget {
const Tapbox({super.key, this.active = false, required this.onChanged});
final bool active;
final ValueChanged<bool> onChanged;
@override
State<StatefulWidget> createState() {
return _TapboxState();
}
}
class _TapboxState extends State<Tapbox> {
bool _hightlight = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
onTapDown: _handleTapDown,
onTapUp: _handleTapUp,
onTapCancel: _handleTapCancal,
child: Container(
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: widget.active ? Colors.lightGreen[700] : Colors.grey[600],
border: _hightlight
? Border.all(color: Colors.teal, width: 10.0)
: null),
child: Center(
child: Text(
widget.active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
),
);
}
void _handleTap() {
widget.onChanged(!widget.active);
}
void _handleTapDown(TapDownDetails details) {
setState(() {
_hightlight = true;
});
}
void _handleTapUp(TapUpDetails details) {
setState(() {
_hightlight = false;
});
}
void _handleTapCancal() {
setState(() {
_hightlight = false;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment