how to control slider with add and subtract buttons in flutter UI
Try this code :
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
double _currentSliderValue = 20;
int divisons=20;
#override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
IconButton(
icon: Icon(Icons.remove),
onPressed: () {
setState(() {
_currentSliderValue -= divisons;
});
},
),
Text(_currentSliderValue.toString()),
IconButton(
icon: Icon(Icons.add),
onPressed: () {
setState(() {
_currentSliderValue += divisons;
});
},
),
],
),
Slider(
value: _currentSliderValue,
max: 100,
divisions: 5,
label: _currentSliderValue.round().toString(),
onChanged: (double value) {
setState(() {
_currentSliderValue = value;
});
},
),
],
);
}
}
Hope this helps.
Simplified sample
class MyWidget extends StatefulWidget{
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int _value = 5;
double min = 1.0;
double max = 20.0;
#override
Widget build(BuildContext context) {
return Column(
children:[
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children:[
IconButton(onPressed:(){
setState((){
if(_value < max){
/// Add as many as you want
_value++;
}
});
}, icon: const Icon(Icons.add)),
IconButton(onPressed:(){
setState((){
if(_value > min){
/// Subtract as many as you want
_value--;
}
});
}, icon: const Icon(Icons.remove)),
]
),
Slider(
value: _value.toDouble(),
min: min,
max: max,
activeColor: Colors.green,
inactiveColor: Colors.orange,
label: 'Set volume value',
onChanged: (double newValue) {
setState(() {
_value = newValue.round();
});
},
),
]);
}
}
here I have made a demo on learning purpose, it might help u
class _SliderPageState extends State<SliderPage> {
double _currentSliderValue=15.0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(onPressed: (){
setState(() {
if(_currentSliderValue<100)
_currentSliderValue=_currentSliderValue+1;
});
}, icon: Icon(Icons.add)),
Text(_currentSliderValue.round().toString(),style: TextStyle(fontWeight: FontWeight.bold,fontSize: 24),),
IconButton(onPressed: (){
setState(() {
if(_currentSliderValue>1)
_currentSliderValue=_currentSliderValue-1;
});
}, icon: Icon(Icons.remove)),
],),
Slider(
value: _currentSliderValue,
max: 100,
divisions: 100,
//label: _currentSliderValue.round().toString(),
onChanged: (double value) {
setState(() {
_currentSliderValue = value;
});
},
),
],)
),
);
}
}
Related
I'm using audioplayers: 1.1.0 plugin to play audio from url. It's playing well. But the player.onPositionChanged after particular seconds it restarts and timer starts from 0.
So that my slider again starts from 0.
player.onPositionChanged.listen((newPosition) {
prints(newPosition);
});
Output:
0:00:00.000000
0:00:00.002000
0:00:00.203000
0:00:00.405000
0:00:00.607000
0:00:00.810000
0:00:01.013000
0:00:01.215000
0:00:02.027000
0:00:02.232000
0:00:03.863000
0:00:04.882000
0:00:00.236000 // after some seconds again returns from 0
0:00:00.438000
0:00:00.641000
0:00:01.052000
0:00:01.662000
0:00:01.864000
As this function returns again from 0, Slider also restarting as below
This is the entire code
audioplayers: 1.1.0
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:async';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Audio Player'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final player = AudioPlayer();
bool isPlaying = false;
Duration duration = Duration.zero;
Duration position = Duration.zero;
String formatTime(int seconds) {
return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
}
#override
void initState() {
super.initState();
player.onPlayerStateChanged.listen((state) {
setState(() {
isPlaying = state == PlayerState.playing;
});
});
player.onDurationChanged.listen((newDuration) {
setState(() {
duration = newDuration;
});
});
player.onPositionChanged.listen((newPosition) {
setState(() {
position = newPosition;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Slider(
min: 0,
max: duration.inSeconds.toDouble(),
value: position.inSeconds.toDouble(),
onChanged: (value) {
final position = Duration(seconds: value.toInt());
player.seek(position);
player.resume();
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
radius: 25,
child: IconButton(
icon: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
),
onPressed: () {
if (isPlaying) {
player.pause();
} else {
player.play("https://www.kozco.com/tech/LRMonoPhase4.mp3");
}
},
),
),
SizedBox(
width: 20,
),
CircleAvatar(
radius: 25,
child: IconButton(
icon: const Icon(Icons.stop),
onPressed: () {
player.stop();
},
),
),
],
),
Container(
padding: const EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(formatTime(position.inSeconds)),
Text(formatTime((duration - position).inSeconds)),
],
),
),
],
),
),
);
}
}
I have a question about updating Android Emulator after pressing on an icon using setState()
this is my code:
import 'package:flutter/material.dart';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: Text('Dicee'),
backgroundColor: Colors.red,
),
body: DicePage(),
),
),
);
}
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
#override
Widget build(BuildContext context) {
int leftDiceNumber = 1;
return Center(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
setState(() {
leftDiceNumber = 5;
});
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
print('Right button got pressed.');
},
child: Image.asset('images/dice2.png'),
),
),
],
),
);
}
}
and I tried even multiple choices that I found in Stackoverflow , but nothing it's working...
this.setState(() {
leftDiceNumber = 5;
});
WidgetsBinding.instance.addPostFrameCallback((_) => setState(...));
insted of just setState() and didn't work
I want to change the value of leftDiceNumber = 5 when I click on the picture
the initialised value for leftDiceNumber is 1
Put the variable outside the build method.leftDiceNumber, else it will reset on every build.
class DicePage extends StatefulWidget {
#override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNumber = 1; //here
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
setState(() {
leftDiceNumber = 5;
});
},
child: Image.asset('images/dice$leftDiceNumber.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
print('Right button got pressed.');
},
child: Image.asset('images/dice2.png'),
),
),
],
),
);
}
}
I have a code that is responsible for building a menu filter. It allows you to filter data by category and then by subcategory.
Initially, subcategories are in a closed state, but when you click on the arrow, they can be opened. Take a look
But my problem is that if I click on the arrow for any category (Country in my case), then all subcategories open at once. Take a look
It's my code
class _FilterDialogUserState extends State<FilterDialogUser> {
Map<String, List<String>?> filters = {};
bool needRefresh = false;
bool isClickedCountry = false;
#override
void initState() {
super.initState();
filters = widget.initialState;
}
List<FilterItem> children = [
FilterItem('Georgia', subitems: [
FilterItem('Tbilisi'),
FilterItem('Batumi'),
]),
FilterItem('Poland', subitems: [
FilterItem('Warsaw'),
FilterItem('Krakow'),
FilterItem('Wroclaw'),
]),
FilterItem('Armenia', subitems: [
FilterItem('Erevan'),
FilterItem('Gyumri'),
]),
];
// Building a dialog box with filters.
#override
Widget build(BuildContext context) {
return SimpleDialog(
title: const Text('Filters',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25,
fontFamily: 'SuisseIntl',
)),
contentPadding: const EdgeInsets.all(16),
// Defining parameters for filtering.
children: [
Column(
children: children.map(
(e) {
return Column(
children: [
InkWell(
onTap: () async {
setState(() {
isClickedCountry = !isClickedCountry;
});
},
child: Row(
children: [
Checkbox(
value: e.selected,
onChanged: (value) => setState(() {
e.subitems.forEach((element) =>
element.selected = value as bool);
e.selected = value as bool;
}),
),
Text(e.text),
const Spacer(),
isClickedCountry
? const Icon(Icons.arrow_circle_up)
: const Icon(Icons.arrow_circle_down)
],
),
),
if (e.subitems.isNotEmpty)
!isClickedCountry
? Container()
: Padding(
padding: const EdgeInsets.fromLTRB(30, 0, 0, 0),
child: Column(
children: e.subitems.map((e) {
return Row(children: [
Checkbox(
value: e.selected,
onChanged: (value) => setState(() {
e.selected = value as bool;
}),
),
Text(e.text),
]);
}).toList(),
),
)
],
);
},
).toList(),
),
]);
}
}
class FilterItem {
final String text;
bool selected;
List<FilterItem> subitems;
FilterItem(
this.text, {
this.selected = false,
this.subitems = const [],
});
}
Tell me, is it possible to change my code so that not all subcategories are opened, but only the one that the user clicks on?
The each main filter item must be controlled one by one.
Define List isClickedCountry variable
Save and load state from List isClickedCountry variable
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget _buildBody() {
return FilterDialogUser();
}
}
class FilterDialogUser extends StatefulWidget {
FilterDialogUser({Key key}) : super(key: key);
#override
State<FilterDialogUser> createState() => _FilterDialogUserState();
}
class _FilterDialogUserState extends State<FilterDialogUser> {
Map<String, List<String>> filters = {};
bool needRefresh = false;
List<bool> isClickedCountry = List.filled(3, false);
#override
void initState() {
super.initState();
// filters = widget.initialState;
}
List<FilterItem> children = [
FilterItem('Georgia', subitems: [
FilterItem('Tbilisi'),
FilterItem('Batumi'),
]),
FilterItem('Poland', subitems: [
FilterItem('Warsaw'),
FilterItem('Krakow'),
FilterItem('Wroclaw'),
]),
FilterItem('Armenia', subitems: [
FilterItem('Erevan'),
FilterItem('Gyumri'),
]),
];
// Building a dialog box with filters.
#override
Widget build(BuildContext context) {
return SimpleDialog(
title: const Text('Filters',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25,
fontFamily: 'SuisseIntl',
)),
contentPadding: const EdgeInsets.all(16),
// Defining parameters for filtering.
children: [
Column(
children: children.map(
(e) {
final int index = children.indexOf(e);
return Column(
children: [
InkWell(
onTap: () async {
setState(() {
isClickedCountry[index] = !isClickedCountry[index];
});
},
child: Row(
children: [
Checkbox(
value: e.selected,
onChanged: (value) => setState(() {
e.subitems.forEach((element) =>
element.selected = value as bool);
e.selected = value as bool;
}),
),
Text(e.text),
const Spacer(),
isClickedCountry[index]
? const Icon(Icons.arrow_circle_up)
: const Icon(Icons.arrow_circle_down)
],
),
),
if (e.subitems.isNotEmpty)
!isClickedCountry[index]
? Container()
: Padding(
padding: const EdgeInsets.fromLTRB(30, 0, 0, 0),
child: Column(
children: e.subitems.map((e) {
return Row(children: [
Checkbox(
value: e.selected,
onChanged: (value) => setState(() {
e.selected = value as bool;
}),
),
Text(e.text),
]);
}).toList(),
),
)
],
);
},
).toList(),
),
]);
}
}
class FilterItem {
final String text;
bool selected;
List<FilterItem> subitems;
FilterItem(
this.text, {
this.selected = false,
this.subitems = const [],
});
}
So i need to receive data from my RadioDialog stf widget to BoxScreen widget.
I want to show different text depends of random value from boxItems, what i do on this line _randomBoxItem == boxOptionValue ? Text('text1') : Text('text2'),
And i dont know how to get value from _boxOption to boxOptionValue like exmple.
Here is my code:
class BoxScreen extends StatefulWidget {
const BoxScreen({Key? key}) : super(key: key);
static const routeName = '/box';
#override
State<BoxScreen> createState() => _BoxScreenState();
}
class _BoxScreenState extends State<BoxScreen> {
String? boxOptionValue;
final List<String> boxItems = [
'Banana',
'Apple',
'Orange',
];
Future<void> whatIsInTheBox(BuildContext context) async {
return await showDialog(
context: context,
builder: (BuildContext context) => const RadioDialog(),
);
}
#override
Widget build(BuildContext context) {
final String _randomBoxItem = (boxItems..shuffle()).first;
return Scaffold(
appBar: AppBar( title: const Text('BOX Game'),),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(_randomBoxItem),
_randomBoxItem == boxOptionValue ? Text('text1') : Text('text2'),
ElevatedButton.icon(
icon: const Icon(Icons.play_arrow_rounded),
onPressed: () {
whatIsInTheBox(context);
},
label: const Text('What is in BOX?'),
),
],
),
);
}
}
class RadioDialog extends StatefulWidget {
const RadioDialog({Key? key}) : super(key: key);
#override
State createState() => RadioDialogState();
}
class RadioDialogState extends State<RadioDialog> {
// SingingCharacter? _character = SingingCharacter.banana;
String? _boxOption;
void _handleBoxItemChange(String? value) {
setState(() {
_boxOption = value;
});
}
#override
Widget build(BuildContext context) {
return AlertDialog(
contentPadding: const EdgeInsets.symmetric(horizontal: 0, vertical: 10),
title: const Text('Select option'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
RadioListTile<String>(
title: const Text('Banana'),
value: 'Banana',
groupValue: _boxOption,
onChanged: _handleBoxItemChange,
),
RadioListTile<String>(
title: const Text('Apple'),
value: 'Apple',
groupValue: _boxOption,
onChanged: _handleBoxItemChange,
),
RadioListTile<String>(
title: const Text('Orange'),
value: 'Orange',
groupValue: _boxOption,
onChanged: _handleBoxItemChange,
),
],
),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('I choose this!'),
),
],
);
}
}
I am with Flutter 2 month. Thanks
In the widget calling the dialog:
someVariable = await showDialog(...);
In the dialog widget:
Navigator.of(context).pop(returnedValue);
Are you able to declare a string outside of your widgets? Then you should be able to use it like so..
String newValue = ''; //**define a string outside the widgets**
class BoxScreen extends StatefulWidget {
const BoxScreen({Key? key}) : super(key: key);
static const routeName = '/box';
#override
State<BoxScreen> createState() => _BoxScreenState();
}
class _BoxScreenState extends State<BoxScreen> {
String? boxOptionValue;
final List<String> boxItems = [
'Banana',
'Apple',
'Orange',
];
Future<void> whatIsInTheBox(BuildContext context) async {
return await showDialog(
context: context,
builder: (BuildContext context) => const RadioDialog(),
);
}
#override
Widget build(BuildContext context) {
final String _randomBoxItem = (boxItems..shuffle()).first;
return Scaffold(
appBar: AppBar( title: const Text('BOX Game'),),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(_randomBoxItem),
_randomBoxItem == boxOptionValue ? Text('text1') : Text('text2'),
ElevatedButton.icon(
icon: const Icon(Icons.play_arrow_rounded),
onPressed: () {
whatIsInTheBox(context);
},
label: const Text('What is in BOX?'),
),
],
),
);
}
}
class RadioDialog extends StatefulWidget {
const RadioDialog({Key? key}) : super(key: key);
#override
State createState() => RadioDialogState();
}
class RadioDialogState extends State<RadioDialog> {
// SingingCharacter? _character = SingingCharacter.banana;
String? _boxOption;
void _handleBoxItemChange(String? value) {
setState(() {
newValue = value; //**Make it equal the new value**
});
}
#override
Widget build(BuildContext context) {
return AlertDialog(
contentPadding: const EdgeInsets.symmetric(horizontal: 0, vertical: 10),
title: Text(newValue), //**use it in any widget like this**
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
RadioListTile<String>(
title: const Text('Banana'),
value: 'Banana',
groupValue: _boxOption,
onChanged: _handleBoxItemChange,
),
RadioListTile<String>(
title: const Text('Apple'),
value: 'Apple',
groupValue: _boxOption,
onChanged: _handleBoxItemChange,
),
RadioListTile<String>(
title: const Text('Orange'),
value: 'Orange',
groupValue: _boxOption,
onChanged: _handleBoxItemChange,
),
],
),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('I choose this!'),
),
],
);
}
}
I want to make a design in which by clicking on the bottom sheet it will show radio buttons. When I select the radio button it will open the date picker. Below is my code when I click on the radio button it is not selecting the radio button. I am new in flutter so can someone helps me find the mistake in the code?
import 'package:flutter/material.dart';
import 'BottomSheetWidget.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(title: 'Flutter Demo', home: HomeView());
}
}
class HomeView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: MyFloatingButton(),
);
}
}
class MyFloatingButton extends StatefulWidget {
#override
_MyFloatingButtonState createState() => _MyFloatingButtonState();
}
class _MyFloatingButtonState extends State<MyFloatingButton> {
bool _show = true;
#override
Widget build(BuildContext context) {
int _radioValue = 0;
/* var sheetController = showBottomSheet(
context: context,
builder: (context) => BottomSheetWidget());*/
void _handleRadioValueChange(int value) {
setState(() {
_radioValue = value;
});
print("first"+value.toString()+"radiovalue" +_radioValue.toString());
}
return Container(
margin: EdgeInsets.all(10.0),
child: new Wrap(
children: <Widget>[
Center(
child: Container(
height: 3.0, width: 40.0, color: Color(0xFF32335C))),
SizedBox(
height: 10.0,
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Radio(
value: 0,
groupValue: _radioValue,
onChanged: (value) {setState(() {
_radioValue=value;
});
print("radiofirst"+value.toString()+"radiovalue" +_radioValue.toString());
_handleRadioValueChange(value);
},
),
new Text(
'Single Date',
style: new TextStyle(fontSize: 16.0),
),
new Radio(
value: 1,
groupValue: _radioValue,
onChanged: (value) {setState(() {
_radioValue=value;
});
print("radiosecond "+value.toString()+"radiovalue " +_radioValue.toString());
_handleRadioValueChange(value);
},
),
new Text(
'Dual Date',
style: new TextStyle(
fontSize: 16.0,
),
),
],
),
],
),
);
}
}
You can copy paste run full code below
You can move out int _radioValue = 0; and _handleRadioValueChange from build
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(title: 'Flutter Demo', home: HomeView());
}
}
class HomeView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: MyFloatingButton(),
);
}
}
class MyFloatingButton extends StatefulWidget {
#override
_MyFloatingButtonState createState() => _MyFloatingButtonState();
}
class _MyFloatingButtonState extends State<MyFloatingButton> {
bool _show = true;
int _radioValue = 0;
/* var sheetController = showBottomSheet(
context: context,
builder: (context) => BottomSheetWidget());*/
void _handleRadioValueChange(int value) {
setState(() {
_radioValue = value;
});
print("first" + value.toString() + "radiovalue" + _radioValue.toString());
}
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
child: Wrap(
children: <Widget>[
Center(
child: Container(
height: 3.0, width: 40.0, color: Color(0xFF32335C))),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Radio(
value: 0,
groupValue: _radioValue,
onChanged: (value) {
setState(() {
_radioValue = value;
});
print("radiofirst" +
value.toString() +
"radiovalue" +
_radioValue.toString());
_handleRadioValueChange(value);
},
),
Text(
'Single Date',
style: TextStyle(fontSize: 16.0),
),
Radio(
value: 1,
groupValue: _radioValue,
onChanged: (value) {
setState(() {
_radioValue = value;
});
print("radiosecond " +
value.toString() +
"radiovalue " +
_radioValue.toString());
_handleRadioValueChange(value);
},
),
Text(
'Dual Date',
style: TextStyle(
fontSize: 16.0,
),
),
],
),
],
),
);
}
}