Skip to content

Instantly share code, notes, and snippets.

@Hecatoncheir
Last active January 16, 2020 14:47
Show Gist options
  • Save Hecatoncheir/9a029aff04cdf3972ffbb90c9907347c to your computer and use it in GitHub Desktop.
Save Hecatoncheir/9a029aff04cdf3972ffbb90c9907347c to your computer and use it in GitHub Desktop.
import "dart:async";
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final _pressed = StreamController<Map<String, dynamic>>();
final pressed = _pressed.stream.asBroadcastStream();
void onSelect(int id, bool isSelected) =>
_pressed.add({'id': id, 'isSelected': isSelected});
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
MySelectButton(0, onSelect, pressed),
MySelectButton(1, onSelect, pressed),
],
),
Row(
children: <Widget>[
MySelectButton(2, onSelect, pressed),
MySelectButton(3, onSelect, pressed),
],
),
],
)),
),
);
}
}
class MySelectButton extends StatefulWidget {
final Function onPressed;
Stream<Map<String, dynamic>> select;
final int id;
MySelectButton(this.id, this.onPressed, this.select);
@override
_MySelectButtonState createState() => _MySelectButtonState();
}
class _MySelectButtonState extends State<MySelectButton> {
StreamController<bool> _isSelected = StreamController();
Stream<bool> isSelected;
@override
void initState() {
super.initState();
_isSelected = StreamController();
isSelected = _isSelected.stream;
widget.select.listen((id) {
if (id['id'] == widget.id) {
_isSelected.add(id['isSelected']);
} else {
_isSelected.add(false);
}
});
}
@override
void dispose() {
_isSelected.close();
super.dispose();
}
bool selected = false;
@override
Widget build(BuildContext context) {
return StreamBuilder<bool>(
key: Key('button_${widget.id}'),
stream: isSelected,
initialData: selected,
builder: (context, snapshot) {
return Padding(
key: Key('button_${widget.id}'),
padding: EdgeInsets.all(10.0),
child: GestureDetector(
onTap: () {
selected = !selected;
widget.onPressed(widget.id, selected);
},
child: Container(
width: 300.0,
height: 100.0,
color: snapshot.data ? Colors.redAccent : Colors.blueAccent,
)),
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment