Skip to content

Instantly share code, notes, and snippets.

@RyouMon
Last active November 6, 2022 09:56
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/7f1ef8b02f450294d04da7bb1d724d8e to your computer and use it in GitHub Desktop.
Save RyouMon/7f1ef8b02f450294d04da7bb1d724d8e to your computer and use it in GitHub Desktop.
Parent manage states
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;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return Tapbox(
active: _active,
onChanged: _handleTapboxChanged,
);
}
}
class Tapbox extends StatelessWidget {
const Tapbox({super.key, this.active = false, required this.onChanged});
final bool active;
final ValueChanged<bool> onChanged;
void _handleTap() {
onChanged(!active);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600]),
child: Center(
child: Text(
active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment