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
Related
I have the following code where i have buttons. i wpould like to get the numbers of the buttons to store the data and then also display the values on the screen in the text boxes in the order of them being inputted.
I will later on need to store the data in a DB when a user clicks next
How many numbers can be pressed will depend on a variable so it can vary between 1 and 12 numbers before hitting next.
I number which has been inputted should also be able to be changed. Should they then be a button aswell or how would i go about this?
THanks so much for the help
import 'package:flutter/material.dart';
import 'package:flutter_grid_button/flutter_grid_button.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.purple,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
Size screenSize(BuildContext context) {
return MediaQuery.of(context).size;
}
double screenHeight(BuildContext context, {double dividedBy = 1}) {
return screenSize(context).height / dividedBy;
}
double screenWidth(BuildContext context, {double dividedBy = 1}) {
return screenSize(context).width / dividedBy;
}
List<String> test =[];
#override
Widget build(BuildContext context) {
const textStyle = TextStyle(fontSize: 26);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('VIS Scoring'),
),
body: Builder(builder: (context) {
return Padding(
padding: EdgeInsets.only(top: 15, bottom: 0, left: 5, right: 5),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if(test == [])...[
Text("A is greater than 10"),
]else...[
Text("A is less than or Equal to 10")
],
Text(
"Hello World",
),
Text(
test.toString(),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Hello World",
),
Text(
"Hello World",
),
Text(
"Hello World",
),
],
),
Expanded(
//padding: const EdgeInsets.all(18.0),
child: GridButton(
textStyle: textStyle,
borderColor: Colors.grey[300],
borderWidth: 2,
onPressed: (dynamic val) {
test.add(val);
print(test);
// ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(
// content: Text(val.toString()),
// duration: Duration(milliseconds: 4000),
// ),
//
// );
},
items: [
[
GridButtonItem(
title: "9",
),
GridButtonItem(
title: "10",
),
GridButtonItem(
title: "X",
),
],
[
GridButtonItem(
title: "6",
),
GridButtonItem(
title: "7",
),
GridButtonItem(
title: "8",
),
],
[
GridButtonItem(
title: "3",
),
GridButtonItem(
title: "4",
),
GridButtonItem(
title: "5",
),
],
[
GridButtonItem(
title: "0",
),
GridButtonItem(
title: "1",
color: Colors.white,
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
GridButtonItem(
title: "2",
color: Colors.white,
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
],
[],
[
GridButtonItem(
title: "Back",
color: Colors.blue[900],
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
GridButtonItem(
title: "Next",
color: Colors.deepOrangeAccent,
textStyle: textStyle.copyWith(
color: Colors.black, fontWeight: FontWeight.bold),
),
]
],
),
),
],
),
);
}),
),
);
}
}
You can use List and store data there - according to order of button beign pressed.
When you press button there should be some function which checks if button should be pressed or how many times. Maybe same as in 3)
When you put data into the list you can use SetState to update values in TextBoxes
I am trying to make a simple calendar app in Flutter. He had no problems installing the dependencies, but when he tried to add events he couldn't. It used Date.Time.now with no problem, but when it tried to do it with a specific date it failed. I would appreciate someone who could help me. Thanks a lot
import 'package:flutter_clean_calendar/flutter_clean_calendar.dart';
class MoonCalendar extends StatefulWidget {
#override
_MoonCalendarState createState() => _MoonCalendarState();
}
class _MoonCalendarState extends State<MoonCalendar> {
DateTime selectedDay;
List <CleanCalendarEvent> selectedEvent;
final Map<DateTime,List<CleanCalendarEvent>> events = {
DateTime (DateTime.utc(2022).year,DateTime.utc(07).month,DateTime.utc(15).day):
[
CleanCalendarEvent(
'Event A',
startTime: DateTime(
DateTime.utc(2022).year,DateTime.utc(7).month,DateTime.utc(15).day,10,0),
endTime: DateTime(
DateTime.utc(2022).year,DateTime.utc(7).month,DateTime.utc(15).day,12,0),
description: 'A special event',
color: Colors.blue[700]),
],
};
void _handleData(date){
setState(() {
selectedDay = date;
selectedEvent = events[selectedDay] ?? [];
});
print(selectedDay);
}
#override
void initState() {
// TODO: implement initState
selectedEvent = events[selectedDay] ?? [];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Calendario",
style: TextStyle(fontSize: 22),
),
Text(
" Lunar",
style: TextStyle(fontSize: 22, color: Color.fromRGBO(56, 215, 199, 1)),
)
],
),
),
body: SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
Color.fromRGBO(61, 138, 146, 0.2),
Color.fromRGBO(56, 215, 199, 0.1)
]
)
),
child: Calendar(
startOnMonday: true,
selectedColor: Colors.blue,
todayColor: Colors.red,
eventColor: Colors.green,
eventDoneColor: Colors.amber,
bottomBarColor: Colors.deepOrange,
onRangeSelected: (range) {
print('selected Day ${range.from},${range.to}');
},
onDateSelected: (date){
return _handleData(date);
},
events: events,
isExpanded: true,
dayOfWeekStyle: TextStyle(
fontSize: 15,
color: Colors.black12,
fontWeight: FontWeight.w100,
),
bottomBarTextStyle: TextStyle(
color: Colors.black87,
),
hideBottomBar: false,
hideArrows: false,
weekDays: ['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'],
),
),
),
);
}
} ```
how can i change color of these iconbuttons by pressing it, please help me and show me whole code for it,
Thanks
In setState you have to add boolean variable, for example changeColor = false;
Then in button :
color: changeColor ? Colors.grey : Colors.blue,
onPressed: () => setState(() => changeColor = !changeColor),
Flutter - How do I toggle the color of a RaisedButton upon click?
This is new method to change color,
there is youtube video for this Here and a article for this Article
ElevatedButton(
child: Text('Elevated Button'),
onPressed: () {
print('Pressed');
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) return Colors.green;
return Colors.greenAccent;
},
),
),
)
You can change the background color of the ElevatedButton using MaterialStateProperty class. You can change the color of the button based on the states too. See the code snippet given below.
IconButton in flutter has a color variable you can set as here:
IconButton(
color: Colors.green,
icon: Icon(Icons.camera),
onPressed: () {},
)
This is the code that I would use:
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: MyWidget(),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: SingleChildScrollView(
child: Column(children: [
const Text(
'Choose Category',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
Row(children: [
CategoryButton(
svg: 'assets/candy.svg',
label: 'Tech',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'Finance',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'Design',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'File',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'Music',
selected: false,
),
])
]),
),
),
);
}
}
class CategoryButton extends StatefulWidget {
CategoryButton({
Key? key,
required this.svg,
required this.label,
required this.selected,
}) : super(key: key);
String svg;
String label;
bool selected;
#override
State<CategoryButton> createState() => _CategoryButtonState();
}
class _CategoryButtonState extends State<CategoryButton> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
widget.selected = !widget.selected;
});
print(widget.selected);
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
color: widget.selected ? Colors.blue : Colors.black,
borderRadius: BorderRadius.circular(90),
),
child: Column(
children: [
SvgPicture.asset(widget.svg,
color: widget.selected ? Colors.white : Colors.blue),
Text(
widget.label,
style: TextStyle(
color: Colors.white,
fontSize: 9,
fontWeight: FontWeight.w500,
),
),
],
)),
);
}
}
here you need to make sure to add flutter_svg to your pubspec.yaml file and have a folder for your assets and add that to your pubspec.yaml file as well
if you have any further questions just ask :)
Hello friend I am retrieve json data in my list view this json file inside my assets folder now I want implement search bar in my flutter application please help how to resolve this this issue its very important part in my app I have 500+ words in my flutter application so user search specific word through search bar any expert is here who can help me
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'package:hebrew/dictinary/Meaning.dart';
class Dictionary extends StatefulWidget {
#override
_DictionaryState createState() => _DictionaryState();
}
class _DictionaryState extends State<Dictionary> {
List data=[];
List searchword=[];
Future<String>loadjsondata()async{
var jsonText=await rootBundle.loadString('assets/hebrew.json');
setState(() {
data=json.decode(jsonText);
});
print(jsonText);
}
#override
void initState() {
super.initState();
setState(() {
loadjsondata();
});
}
bool issearching=false;
void _filtwewords(value){
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:!issearching ?Text('Hebrew Dictionary')
: TextField(
onChanged: (value) {
_filtwewords(value);
},
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
icon: Icon(
Icons.search,
color: Colors.white,
),
hintText: "Search Words...",
hintStyle: TextStyle(color: Colors.white)),
),
actions:<Widget> [
this.issearching ? IconButton(
icon: Icon(Icons.cancel),
onPressed: () {
setState(() {
this.issearching = false;
});
},
)
: IconButton(
icon: Icon(Icons.search),
onPressed: () {
setState(() {
this.issearching =true;
});
},
)
],
),
body:Padding(
padding:EdgeInsets.all(5),
child: new ListView.separated(
separatorBuilder: (context, index) => Divider(
),
itemCount:data==null ? 0 :data.length,
itemBuilder: (BuildContext ctxt, int index) {
return Padding(
padding: EdgeInsets.all(4),
child: Column(
crossAxisAlignment:CrossAxisAlignment.stretch,
children: [
SizedBox(height: 10,),
GestureDetector(
onTap: () {
Navigator.push (context,MaterialPageRoute(builder: (context) =>Meaning(data[index]['eng'],data[index]['hebrew'],data[index]['urdu'])));
},
child: Text(data[index]['eng'],style: TextStyle(
fontSize: 15
),),
),
],
),
);
}
),
)
);
}
}
So I just made a code for search data using the local JSON file. First I created an empty list and all data in that list one by one and created a listview. After that created a TextField and check if textfield is empty then show full data else added search data in another list and show this data on listview
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: SelectionScreen(),
);
}
}
class SelectionScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _selectionScreen();
}
}
class _selectionScreen extends State<SelectionScreen> {
List fullData = new List();
List searchData = new List();
TextEditingController textEditingController = new TextEditingController();
#override
initState() {
super.initState();
getLocalJsonData();
}
getLocalJson() {
return rootBundle.loadString('assets/data.json'); // Read your local Data
}
Future getLocalJsonData() async {
final responce = json.decode(await getLocalJson());
List tempList = new List();
for (var i in responce['data']) {
tempList.add(i); // Create a list and add data one by one
}
fullData = tempList;
}
onSearchTextChanged(String text) async {
searchData.clear();
if (text.isEmpty) { // Check textfield is empty or not
setState(() {});
return;
}
fullData.forEach((data) {
if (data['Title']
.toString()
.toLowerCase()
.contains(text.toLowerCase().toString())) {
searchData.add(data); // If not empty then add search data into search data list
}
});
setState(() {});
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: InkWell(
child: Text("Search With Local Data"),
),
),
body: Container(
child: Column(
children: [
TextField(
controller: textEditingController,
onChanged: onSearchTextChanged,
),
Expanded(
child: searchData.length == 0 // Check SearchData list is empty or not if empty then show full data else show search data
? ListView.builder(
itemCount: fullData.length,
itemBuilder: (context, int index) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
spreadRadius: 2,
offset: Offset(2, 2))
]),
margin: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Post",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16),
),
Container(
height: 2,
),
Text(fullData[index]['Title'])
],
),
);
},
)
: ListView.builder(
itemCount: searchData.length,
itemBuilder: (context, int index) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
spreadRadius: 2,
offset: Offset(2, 2))
]),
margin: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Post",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16),
),
Container(
height: 2,
),
Text(searchData[index]['Title'])
],
),
);
},
),
)
],
)),
);
}
}
And here is my local data.json file
{
"data": [
{
"Id": 1,
"Title": "ABC",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "CDF",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "EFG",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "ABCD",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "PQR",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "RNDS",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "qwer",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
},
{
"Id": 1,
"Title": "asdad",
"Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
}
]
}
I wanna ask you about flutter.
what I want to do is make some quiz app with this class
this class is made for quiz part view.
I want to make the buttons named 'RaisedButton' are for answers and when they pressed, then changing _questionInd, the page is refreshed with the contents changing. what can I do for this goal? :(
This is for a Quiz app made by dart language and flutter framework.
class _SolvingPage extends MaterialPageRoute<Null> {
int ind=0;
int _questionInd=0;
void _answerQuestion(){
setState((){
_questionInd+=1;
});
print(_questionInd);
}
_SolvingPage()
: super(builder: (BuildContext context) {
var questions = [
{
'questionText': 'What\'s your favorite color?',
'answers': ['Black', 'Red', 'Green', 'White'],
},
{
'questionText': 'What\'s your favorite animal?',
'answers': ['Rabbit', 'Snake', 'Elephant', 'Lion'],
},
{
'questionText': 'Who\'s your favorite instructor?',
'answers': ['Max', 'Max', 'Max', 'Max'],
},
];
return Scaffold(
appBar: AppBar(
title: Text('문제풀이 페이지'),
backgroundColor: Colors.pinkAccent,
elevation: 0.5,
toolbarOpacity: 0.8,
// prototype에서는 이 제목 바는 없고, 하단에 정지 아이콘을 두었음
),
body: Builder(
builder: (BuildContext context) => Center(
child: Column(
children:<Widget>[
Container(
width: 300,
height: 300,
decoration:BoxDecoration(
border:Border.all(width:1.5, color: Colors.white70),
color: Colors.white70,
borderRadius: BorderRadius.circular(15.0),
),
alignment: Alignment.center,
child: Text('1'),
),
Text('1'),
RaisedButton(
child: Text('1'),
onPressed:(){
//다음 문제로 넘어가야 함
int temp=_SolvingPage()._questionInd++;
print('$temp');
},
color: Colors.white,
),
RaisedButton(
child: Text('1'),
onPressed:(){
},
color: Colors.white,
),
RaisedButton(
child: Text('1'),
onPressed:(){
},
color: Colors.white,
),
Row(
//문제 넘기기 버튼, 정지 버튼
//문제 넘기기 버튼, 정지 버튼
),
]
)
)
)
);
});
}
화면을 바꾸기 위해서는
setState(() {
});
를 이용해야합니다
String quiz = "문제1";
Text(quiz);
setState(() {
quiz = "문제2";
});