
Flutter switch widget
Introduction
In this tutorial, I show you how to use Switch Widget in flutter using Stream Builder.
Switch Widget
If you are a programmer, and so I think you well know about switch if you don’t know then don’t worry I will tell you.
The switch is a widget in flutter who returns a value in Boolean form means true or false.
You don’t have a need to include any third-party library for use a Switch Widget it is already provided by flutter.
Start
First, we have created a file and initialize Stream Controller
import 'package:rxdart/rxdart.dart';
class Bloc{
//initialize bool type controller
final _switchController = BehaviorSubject<bool>();
/// Add data to the stream
Function(bool) get setSwitch => _switchController.sink.add;
/// Validate and retrieve data from the stream
Stream<bool> get getSwitch => _switchController.stream;
}Then import Bloc.dart file in your class where you want to add Switch Widget
import 'package:bloc_flutter_switch/Bloc.dart';
Create an object of Bloc.dart file
Bloc bloc=Bloc();
Add below code where you want to add a switch
StreamBuilder(
stream: bloc.getSwitch,
builder: (context,snapshot){
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("${snapshot.data??false}"),
Switch(
value: snapshot.data??false,
activeColor: Colors.green,
onChanged: (b) {
bloc.setSwitch(b);
},
)
],
);
})Output




