Select-DeSelect Buttons in Flutter - flutter

I want to create below tab like rounded buttons named Vehicle & Key in flutter which is selectable and de-selectable. I can use Tab but its part of scaffold. Is there any other way to achieve as below?

You can use the toggle_switch 2.0.1 (https://pub.dev/packages/toggle_switch) package which is in Flutter favorite program.
Its simple to use : -
ToggleSwitch(
minWidth: 200.0,
minHeight: 55.0,
cornerRadius: 35.0,
activeBgColors: const [
[Color.fromARGB(255, 52, 26, 94)],
[Color.fromARGB(255, 52, 26, 94)]
],
borderColor: const [Color.fromARGB(255, 154, 207, 251)],
borderWidth: 0.7,
inactiveBgColor: Colors.white,
inactiveFgColor: const Color.fromARGB(255, 52, 26, 94),
initialLabelIndex: 0,
totalSwitches: 2,
labels: const ['Vechile', 'Key'],
radiusStyle: true,
onToggle: (index) {},
),
Complete Code : -
import 'package:flutter/material.dart';
import 'package:toggle_switch/toggle_switch.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 const MaterialApp(
debugShowCheckedModeBanner: false,
title: _title,
home: ToggleSwitchButton(),
);
}
}
class ToggleSwitchButton extends StatefulWidget {
const ToggleSwitchButton({Key? key}) : super(key: key);
#override
_ToggleSwitchButtonState createState() => _ToggleSwitchButtonState();
}
class _ToggleSwitchButtonState extends State<ToggleSwitchButton> {
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Center(
child: ToggleSwitch(
minWidth: 200.0,
minHeight: 55.0,
cornerRadius: 35.0,
activeBgColors: const [
[Color.fromARGB(255, 52, 26, 94)],
[Color.fromARGB(255, 52, 26, 94)]
],
borderColor: const [Color.fromARGB(255, 154, 207, 251)],
borderWidth: 0.7,
inactiveBgColor: Colors.white,
inactiveFgColor: const Color.fromARGB(255, 52, 26, 94),
initialLabelIndex: 0,
totalSwitches: 2,
labels: const ['Vechile', 'Key'],
radiusStyle: true,
onToggle: (index) {},
),
)),
);
}
}
Output : -

You can create two widgets simultaneously and then provide them a flag for visibility :
Column(
children: [
Row(
children: [
ElevatedButton(
onPressed: (() => flag=true),
child: Text("Vehicle"),),
ElevatedButton(
onPressed: (() => flag=false),
child: Text("Vehicle"),),
]),
flag ? Child1 : Child2,
],
),
This can help you create two buttons which onPressing will change your flag which in turn will change the content you are providing on the screen.

Related

Why me trackball always disappears when I move a mouse on a SfCartesianChart?

I have SfCartesianChart and trackball inside, when I try to click or move a mouse on the SfCartesianChart then nothing happens, my trackball doesn't appear.
It appears only one second then immediately disappears, I fond out it by clicking and moving a mouse on SfCartesianChart almost a minute...
How to fix that?
This is my SfCartesianChart, there is no trackball when I click or move on blue dots:
And this is my code:
class HomeWidget extends StatefulWidget {
const HomeWidget({super.key});
#override
State<HomeWidget> createState() => _HomeWidgetState();
}
class _HomeWidgetState extends State<HomeWidget> {
late TabController _tabController;
void initState() {
_tabController = TabController(vsync: this, length: 3);
super.initState();
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SizedBox(
height: 220.h,
child: TabBarView(
controller: _tabController,
children: [
DaysChart(
monitoringData: state.chartData,
precision: 1
),
DaysChart(
monitoringData: state.chartData,
precision: 2
),
DaysChart(
monitoringData: state.chartData,
precision: 3
),
],
)
);
}
}
Chartdata looks like this:
state.chartData = List<TimeSeriesValues> dayMonitoringData = [
TimeSeriesValues(DateTime(2007, 2, 1, 8, 40), 30),
TimeSeriesValues(DateTime(2007, 2, 1, 12, 40), 80),
TimeSeriesValues(DateTime(2007, 2, 1, 18, 40), 50),
];
And TimeSeriesValues class:
class TimeSeriesValues {
final DateTime time;
final int values;
TimeSeriesValues(this.time, this.values);
}
And this is DaysChart:
class DaysChart extends StatefulWidget {
const DaysChart({
Key? key,
required this.monitoringData,
required this.precision,
}) : super(key: key);
final List<TimeSeriesValues> monitoringData;
final int precision;
#override
State<DaysChart> createState() => _DaysChartState();
}
class _DaysChartState extends State<DaysChart> {
late TrackballBehavior _trackballBehavior;
#override
void initState() {
_trackballBehavior = TrackballBehavior(
enable: true,
shouldAlwaysShow: true,
lineColor: const Color(0xFF454545),
activationMode: ActivationMode.singleTap,
tooltipDisplayMode: TrackballDisplayMode.nearestPoint,
tooltipSettings: const InteractiveTooltip(
arrowLength: 0,
arrowWidth: 0,
canShowMarker: false,
color: Colors.transparent,
),
builder: (context, TrackballDetails trackballDetails) {
var tag = Localizations.maybeLocaleOf(context)?.toLanguageTag();
return SizedBox(
height: 50,
child: Column(
children: [
Text(
"${trackballDetails.point!.yValue.round().toString()}%",
style: TextStyle(
color: Colors.white,
fontSize: 16.sp,
)
),
Text(
DateFormat.MMMMd(tag).format(trackballDetails.point!.x),
style: TextStyle(
color: Colors.white,
fontSize: 10.sp,
),
)
],
)
);
}
);
super.initState();
}
#override
Widget build(BuildContext context) {
final List<double> stops = <double>[];
stops.add(0.1);
stops.add(1.0);
return SizedBox(
height: 190.h,
width: 320.w,
child: SfCartesianChart(
plotAreaBorderWidth: 0,
plotAreaBorderColor: Colors.white24,
trackballBehavior: _trackballBehavior,
primaryXAxis: DateTimeCategoryAxis(
majorTickLines: const MajorTickLines(width: 0),
axisLine: const AxisLine(
color: Colors.white24,
dashArray: <double>[5,5]
),
minimum: widget.monitoringData.first.time,
maximum: widget.monitoringData.last.time,
intervalType: widget.precision == 1
? DateTimeIntervalType.minutes
: widget.precision == 2
? DateTimeIntervalType.days
: DateTimeIntervalType.months,
dateFormat: widget.precision == 1
? DateFormat.Hm()
: widget.precision == 2
? DateFormat.E()
: DateFormat.MMMd(),
borderColor: Colors.transparent,
majorGridLines: const MajorGridLines(
width: 0.5,
color: Colors.transparent,
),
),
primaryYAxis: NumericAxis(
majorGridLines: const MajorGridLines(width: 0.5, color: Colors.white24, dashArray: <double>[5, 5]),
majorTickLines: const MajorTickLines(width: 0),
axisLine: const AxisLine(
width: 0
),
labelStyle: const TextStyle(
fontSize: 0
),
minimum: 0,
maximum: 100
),
series: <ChartSeries<TimeSeriesValues, DateTime>>[
AreaSeries<TimeSeriesValues, DateTime>(
borderWidth: 2,
animationDuration: 0,
borderColor: const Color(0xFF409CFF),
dataSource: widget.monitoringData,
markerSettings: const MarkerSettings(
isVisible: true,
color: Color(0xFF409CFF),
height: 11,
width: 11,
borderWidth: 3,
borderColor: Colors.transparent,
),
xValueMapper: (TimeSeriesValues sales, _) => sales.time,
yValueMapper: (TimeSeriesValues sales, _) => sales.values,
gradient: LinearGradient(
colors: const [Color(0xFF121212), Color(0xFF10273F)],
stops: stops,
begin: Alignment.bottomCenter,
end: Alignment.topCenter),
)
]
);
}

How to call a variable or function from a different file to main.dart in flutter?

I've been trying to implement a similar function like the NavigationBar widget in flutter.
However, I don't want to use Icons instead I wanted to make a custom navbar with desired pics and everything was going well until I couldn't switch the middle section of my app (change different pages) when I tap/press the the textbutton.
You can check the UI here...crappy I know...am mimicking the till from my workplace...so the red section is the part I wanted to update when pressed
The side_buttons.dart file
import 'package:flutter/material.dart';
// ignore: unused_import
import 'package:timtill/main.dart';
class SideButtons extends StatefulWidget {
final String text;
final String imgUrl;
const SideButtons({required this.text, required this.imgUrl});
#override
State<SideButtons> createState() => SideButtonsState();
}
class SideButtonsState extends State<SideButtons> {
//
final List sideBtnLabels = [
'HOT DRINKS',
'COLD DRINKS',
'DONUTS',
'TIMBITS',
'MUFFINS',
'BAGELS',
'SOUP',
'LUNCH',
'BREAK FAST',
'BAKED',
'TAKE-HOME',
'Timmies'
];
#override
Widget build(BuildContext context) {
return Transform.rotate(
angle: -11,
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFF9A9DAD), Color(0xFF4E4C56)])),
height: 80,
width: 80,
child: TextButton(
onPressed: () {
int currentPageIndex = 0;
int index = sideBtnLabels.indexOf(widget.text);
setState(() {
currentPageIndex = index;
});
int navMiddleIndex(int index) {
return index;
}
print(sideBtnLabels.indexOf(widget.text));
// print('index is changed to: ${navMiddleIndex(index).toString()}');
},
//////here Instead of text you can replace Node and import the dart:html
//import 'dart:html';
// text works because in the side_btn_page.dart we have specified the list of menu to it
child: Stack(
alignment: const AlignmentDirectional(0.0, 0.9),
children: [
Image.asset(
'imgs/' + widget.imgUrl,
//imgurl
),
Text(
widget.text, //text
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..color = const Color.fromARGB(255, 63, 63, 63),
),
),
Text(
widget.text, //text
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Color(0xFFEBEBEB),
),
),
],
)),
),
);
}
}
'''
The Main.dart file
Note I wanted to update the currentPageIndex value from zero to the index number When I press the buttons please help me I'm beginner
import 'package:flutter/material.dart';
import 'package:timtill/pages/side_btn_page.dart';
import 'package:timtill/pages/middle_btn_page.dart';
import 'package:timtill/pages/middle_btn_page2.dart';
// ignore: unused_import
import 'package:timtill/util/side_buttons.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'TimsTill',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentPageIndex = 0;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
children: [
SizedBox(height: 80, child: SideButtonPage()),
Expanded(
flex: 12,
child: Container(
color: Colors.red,
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.all(8),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: <Widget>[
MiddleButtonPage(),
MiddleButtonPage2(),
Container(
color: Colors.green,
alignment: Alignment.center,
child: const Text('Page 2'),
),
Container(
color: Colors.blue,
alignment: Alignment.center,
child: const Text('Page 3'),
),
][currentPageIndex],
),
),
),
),
)),
Expanded(
flex: 6,
child: Container(
color: Colors.purple,
))
],
),
);
}
}
First of all, you should implement a callback in your SideButtons widget, second, you should implement the defaultPageIndex. This way, SideButtons will return the selected index to its parent widget while maintening its state incase the widget try is rebuilt.
class SideButtons extends StatefulWidget {
final String text;
final String imgUrl;
final int defaultPageIndex;
final ValueChanged<int>? onChanged;
const SideButtons({required this.text, required this.imgUrl, this.defaultPageIndex = 0, this.onChanged});
#override
State<SideButtons> createState() => SideButtonsState();
}
class SideButtonsState extends State<SideButtons> {
//
final List sideBtnLabels = [
'HOT DRINKS',
'COLD DRINKS',
'DONUTS',
'TIMBITS',
'MUFFINS',
'BAGELS',
'SOUP',
'LUNCH',
'BREAK FAST',
'BAKED',
'TAKE-HOME',
'Timmies'
];
late int currentPageIndex;
#override
initState(){
currentPageIndex = defaultPageIndex;
super.initState();
}
#override
Widget build(BuildContext context) {
return Transform.rotate(
angle: -11,
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFF9A9DAD), Color(0xFF4E4C56)])),
height: 80,
width: 80,
child: TextButton(
onPressed: () {
int index = sideBtnLabels.indexOf(widget.text);
setState(() {
currentPageIndex = index;
if( widget.onChanged != null) widget.onChanged(index);
});
int navMiddleIndex(int index) {
return index;
}
print(sideBtnLabels.indexOf(widget.text));
// print('index is changed to: ${navMiddleIndex(index).toString()}');
},
//////here Instead of text you can replace Node and import the dart:html
//import 'dart:html';
// text works because in the side_btn_page.dart we have specified the list of menu to it
child: Stack(
alignment: const AlignmentDirectional(0.0, 0.9),
children: [
Image.asset(
'imgs/' + widget.imgUrl,
//imgurl
),
Text(
widget.text, //text
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..color = const Color.fromARGB(255, 63, 63, 63),
),
),
Text(
widget.text, //text
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Color(0xFFEBEBEB),
),
),
],
)),
),
);
}
}

How to make scrollable list using array

I am trying to make my code simple by making it into an array instead I have to write it one by one, but I do not have an idea on how to convert it into an array list. Here for what I have been done. My output is I want to generate the list in a container with scrollable to the right using axis horizontal scroll direction.
class YearSort extends StatelessWidget {
final String title;
const YearSort({
Key? key,
required this.title,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
ByYear(year: 'This year'),
ByYear(year: '2021'),
ByYear(year: '2020'),
ByYear(year: '2019'),
ByYear(year: '2018'),
],
),
);
}
}
class ByYear extends StatefulWidget {
final String year;
const ByYear({
Key? key,
required this.year,
}) : super(key: key);
#override
State<ByYear> createState() => _ByYearState();
}
class _ByYearState extends State<ByYear> {
bool iselected = true;
#override
Widget build(BuildContext context) {
return Container(
width: 100,
height: 30,
decoration: BoxDecoration(
color: iselected
? Color.fromARGB(255, 215, 237, 255)
//Colors.white
: Color.fromARGB(255, 215, 237, 255),
borderRadius: BorderRadius.circular(20),
),
child: Center(child: Text(widget.year, style: const TextStyle(fontFamily: 'Poppins'),)),
);
}
}
Your syntax is kind of not correct for a few widgets and incorrect use of Expanded. This one will help you.
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _title.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Container(
width: 70,
height: 30,
decoration: BoxDecoration(
color: isSelected
? Colors.yellow
: Colors.blue,
borderRadius: BorderRadius.circular(20),
),
child: Text(_title[index], style: TextStyle(fontFamily: 'Poppins'),),
);
},
);
}
Since you edit the question in middle of nowhere,
class YearSort extends StatefulWidget {
final String title;
const YearSort({
Key? key,
required this.title,
}) : super(key: key);
#override
State<YearSort> createState() => _YearSortState();
}
class _YearSortState extends State<YearSort> {
int selectedIndex = 0;
static List chips = [
DateTime.now().year,
DateTime.now().year - 1,
DateTime.now().year - 2,
DateTime.now().year - 3,
DateTime.now().year - 4
];
#override
Widget build(BuildContext context) {
return Column(
children: [
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(children: [
for(int index = 0; index < chips.length; index++)
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
child: ByYear(
year: chips[index].toString(),
isSelected: selectedIndex == index,
),
onTap: () {
selectedIndex = index;
setState(() {});
},
),
)
],),
),
Expanded(child: Container())
],
);
}
}
class ByYear extends StatefulWidget {
final String year;
final bool isSelected;
const ByYear({Key? key, required this.year, this.isSelected = false})
: super(key: key);
#override
State<ByYear> createState() => _ByYearState();
}
class _ByYearState extends State<ByYear> {
#override
Widget build(BuildContext context) {
Color color = widget.isSelected
? const Color.fromARGB(255, 25, 27, 25)
: const Color.fromARGB(255, 215, 237, 255);
Color textColor = !widget.isSelected
? const Color.fromARGB(255, 25, 27, 25)
: const Color.fromARGB(255, 215, 237, 255);
return Container(
height: 30,
width: 100,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
widget.year,
style: TextStyle(
fontSize: 16, color: textColor, decoration: TextDecoration.none),
),
),
);
}
}
Note: You can also use Listview.builder instead of singlechildscrollview
If you have an array to show in a scrollable widget, you can use Listview instead of SingleChildScrollView. Like this:
#override
Widget build(BuildContext context) {
return ListView(
scrollDirection: Axis.horizontal,
children: const [
ByYear(year: 'This year'),
ByYear(year: '2021'),
ByYear(year: '2020'),
ByYear(year: '2019'),
ByYear(year: '2018'),
],
shrinkWrap: true,
);
}
hope it helps you.

how to disable tooltip dynamcically in flutter?

I can disable the tooltip statically.
But I want to disable tooltip dynamically when i click flatbutton.But Couldnt disable dynamically and i have no idea to do that.
This is my code:
import 'package:flutter/material.dart';
void main(){
runApp(MaterialApp(home: HelloWorld(),debugShowCheckedModeBanner: false,));
}
class HelloWorld extends StatefulWidget {
#override
_HelloWorldState createState() => _HelloWorldState();
}
class _HelloWorldState extends State<HelloWorld> {
bool check = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(children: <Widget>[
TopToolbar(),
FlatButton(
child: Text("Disable Tooltip"),
onPressed: () {
setState(() {
TopToolbar toolbar = new TopToolbar();
toolbar.showTooltip = false;
});
},
),
]),
),
));
}
}
class TopToolbar extends StatefulWidget {
bool showTooltip;
final Color backgroundColor;
final double height;
bool isVisible;
TopToolbar({
this.height = 55,
this.isVisible = true,
this.backgroundColor = const Color(0xFFEEEEEE),
Key key,this.showTooltip=true,
}) : super(key: key);
#override
_TopToolbarState createState() => _TopToolbarState();
}
class _TopToolbarState extends State<TopToolbar> {
#override
Widget build(BuildContext context) {
if (widget.isVisible) {
return Container(
foregroundDecoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey,
),
),
),
margin: EdgeInsets.only(bottom: 1),
color: widget.backgroundColor,
height: widget.height,
child: Stack(
children: <Widget>[
Positioned(
top: 7,
right: 60,
height: 40,
width: 40,
child: RawMaterialButton(
elevation: 0.0,
fillColor: widget.backgroundColor,
splashColor: Colors.grey[300],
child: IconButton(
icon: Icon(
Icons.bookmark,
color: Colors.grey[500],
size: 25,
),
onPressed: (){},
tooltip: widget.showTooltip ? "Bookmark" : null,
),
onPressed: (){},
),
),
],
),
);
} else {
return Container();
}
}
}
If I give statically false. it works fine.
For example : If add child like TopToolbar(showTooltip : false),it works fine,
But If i give toolbar.showTooltip = false in Flatbutton onPressed method,it doesnt work.
I want to disble it in dynamically. please help me to do that.
we can hide or deactivate tooltip programmatically like below,
Future.delayed(
Duration(seconds: 2),
() {
tooltip?.deactivate();
}
);
Here, we can set time according to your requirement.(Currently, we are set 2 sec.)
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: HelloWorld(),
debugShowCheckedModeBanner: false,
));
}
class HelloWorld extends StatefulWidget {
#override
_HelloWorldState createState() => _HelloWorldState();
}
class _HelloWorldState extends State<HelloWorld> {
bool check = false;
bool showTooltip = true;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(children: <Widget>[
TopToolbar(showTooltip: showTooltip),
FlatButton(
child: Text("Disable Tooltip"),
onPressed: () {
setState(() {
showTooltip = false;
});
},
),
]),
),
));
}
}
class TopToolbar extends StatefulWidget {
final bool showTooltip;
final Color backgroundColor;
final double height;
final bool isVisible;
TopToolbar({
this.height = 55,
this.isVisible = true,
this.backgroundColor = const Color(0xFFEEEEEE),
Key key,
this.showTooltip = true,
}) : super(key: key);
#override
_TopToolbarState createState() => _TopToolbarState();
}
class _TopToolbarState extends State<TopToolbar> {
#override
Widget build(BuildContext context) {
if (widget.isVisible) {
return Container(
foregroundDecoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey,
),
),
),
margin: EdgeInsets.only(bottom: 1),
color: widget.backgroundColor,
height: widget.height,
child: Stack(
children: <Widget>[
Positioned(
top: 7,
right: 60,
height: 40,
width: 40,
child: RawMaterialButton(
elevation: 0.0,
fillColor: widget.backgroundColor,
splashColor: Colors.grey[300],
child: IconButton(
icon: Icon(
Icons.bookmark,
color: Colors.grey[500],
size: 25,
),
onPressed: () {},
tooltip: widget.showTooltip ? 'Bookmark' : null,
),
onPressed: () {},
),
),
],
),
);
} else {
return Container();
}
}
}
I've used this method to hide tooltips:
Tooltip(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0),
),
textStyle: TextStyle(color: Colors.white.withOpacity(0)),
message: 'Certificates',
child: Container()
);
Make the property message='' // empty string
setState((){messageText=''});
Tooltip(
message: messageText,
...
)

Dynamically add widgets to a column's children in flutter

I'm creating a quiz app and need to display mcq options dynamically based on how many options there are for a particular question.
So for example:
Now the code for the buttons is here :
final quizOptions = Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Column(
children: <Widget>[
SimpleRoundButton(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
buttonText: Text(questions[questionNum].options[0],
style: TextStyle(
color: Colors.white
),
),
textColor: Colors.white,
onPressed: (){},
),
SimpleRoundButton(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
buttonText: Text(questions[questionNum].options[1],
style: TextStyle(
color: Colors.white
),
),
textColor: Colors.white,
onPressed: (){},
),
],
),
),
);
As you can see, what I am able to do is to "fix" 2 buttons. Is there a way to dynamically add buttons based on how many options there are for that particular question ?
I have a list named questions and it is a list of questions (which is a class):
class Question {
String title;
List options;
String imagePath;
Question(
{this.title, this.options, this.imagePath,});
}
//Example:
Question(
title: "How fast does the drone go ?",
options: ['80km/h', '90km/h', '100km/h'],
imagePath: "assets/images/drones1.jpg",
)
You should iterate through your options to create SimpleRoundButton
...................................
child: Column(
children: questions[questionNum].options.map<Widget>(
(option) => SimpleRoundButton(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
buttonText: Text(option,
style: TextStyle(
color: Colors.white
),
),
textColor: Colors.white,
onPressed: (){},
),
).toList(),
.........................
I made a complete example that I use dynamic widgets to show and hide widgets on screen, you can see it running online on dart fiddle, too.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List item = [
{"title": "Button One", "color": 50},
{"title": "Button Two", "color": 100},
{"title": "Button Three", "color": 200},
{"title": "No show", "color": 0, "hide": '1'},
];
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Dynamic Widget - List<Widget>"),backgroundColor: Colors.blue),
body: Column(
children: <Widget>[
Center(child: buttonBar()),
Text('Click the buttons to hide it'),
]
)
)
);
}
Widget buttonBar() {
return Column(
children: item.where((e) => e['hide'] != '1').map<Widget>((document) {
return new FlatButton(
child: new Text(document['title']),
color: Color.fromARGB(document['color'], 0, 100, 0),
onPressed: () {
setState(() {
print("click on ${document['title']} lets hide it");
final tile = item.firstWhere((e) => e['title'] == document['title']);
tile['hide'] = '1';
});
},
);
}
).toList());
}
}
Maybe it helps someone. If it was is useful to you, let me know clicking in up arrow, please. Thanks.
https://dartpad.dev/b37b08cc25e0ccdba680090e9ef4b3c1