Related
i have create quiz app, my question page is working properly but i want to display all wrong answers with their correct answers on the result page .I tried to get answers but give me so many errors. first i want display score then click show review answers to see the result page like this that u show on picture i want like this my score and result page
here is my question page
enter code here
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:quiz_app/controllers/profile_controllers.dart';
import 'package:quiz_app/widgets/common_components/appbar.dart';
import 'widgets/pallete.dart';
import 'widgets/rounded_button.dart';
void main() {
runApp(QuestionSample2());
}
class ChosenModel {
final int questionNumber;
final String questionAnswer;
ChosenModel(this.questionNumber, this.questionAnswer);
#override
String toString() {
return '{questionNumber: ${questionNumber}, questionAnswer: ${questionAnswer}}';
}
}
class QuestionControl extends GetxController {
List questions = [
{
"id": 1,
"question":
"Flutter is an open-source UI software development kit created by ______",
"options": ['Apple', 'Google', 'Facebook', 'Microsoft'],
"answer": "Google",
},
{
"id": 2,
"question": "When google release Flutter.",
"options": ['Jun 2017', 'July 2017', 'May 2017', 'May 2018'],
"answer": "Jun 2017",
},
{
"id": 3,
"question": "A memory location that holds a single letter or number.",
"options": ['Double', 'Int', 'Char', 'Word'],
"answer": "Char",
},
{
"id": 4,
"question": "What command do you use to output data to the screen?",
"options": ['Cin', 'Count', 'Cout', 'Output'],
"answer": "Output",
},
].obs;
List<ChosenModel> chosenAnswers = [];
RxList groupValue = [-1, 0, 5, 9, 13].obs;
RxList value = [
[0, 1, 2, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
].obs;
RxInt qnIndex = 1.obs;
}
class QuestionSample2 extends StatelessWidget {
QuestionSample2({Key? key}) : super(key: key);
final QuestionControl controller = Get.put(QuestionControl());
ProfileController _questionController = Get.put(ProfileController());
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color.fromARGB(255, 0, 0, 0),
appBar: quizeAppbar(),
body: Padding(
padding: const EdgeInsets.fromLTRB(5, 15, 5, 10),
child: Column(
children: [
Obx(
() => Text(
controller.qnIndex.toString() +
'/' +
controller.questions.length.toString(),
style: Theme.of(context)
.textTheme
.headline4!
.copyWith(color: Colors.white)),
),
SizedBox(height: 20),
SizedBox(
height: 600.0,
child: PageView.builder(
itemCount: controller.questions.length,
onPageChanged: (pageNumber) {
controller.qnIndex.value = pageNumber + 1;
},
itemBuilder: (context, snapshot) {
var options = controller.questions[snapshot]['options'];
return Container(
margin: const EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: const Color.fromARGB(255, 88, 79, 79),
borderRadius: BorderRadius.circular(15),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Spacer(
flex: 1,
),
Text(
controller.questions[snapshot]['question']
.toString(),
style: Theme.of(context)
.textTheme
.headline5!
.copyWith(color: Colors.white),
),
Spacer(
flex: 2,
),
Container(
height: 400.0,
child: ListView.builder(
itemCount: 4,
itemBuilder: (context, index) => ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
Obx(
() => Container(
width: 300,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(
color: controller.groupValue[
snapshot] ==
controller.value[snapshot]
[index]
? kblue
: Color.fromARGB(
255, 117, 110, 110),
width: 2),
borderRadius:
BorderRadius.circular(15),
),
child: RadioListTile<int>(
activeColor: kblue,
title: Row(
children: [
Text(
options[index].toString(),
style: Theme.of(context)
.textTheme
.headline5!
.copyWith(
color: Colors.white),
),
Spacer(),
],
),
controlAffinity:
ListTileControlAffinity
.trailing,
groupValue:
controller.groupValue[snapshot],
value: controller.value[snapshot]
[index],
onChanged: (newValue) {
controller.groupValue[snapshot] =
newValue as int;
controller.chosenAnswers.add(
ChosenModel(
controller.questions[
snapshot]['id']
as int,
options[index]
.toString()));
print(controller.chosenAnswers);
}),
),
),
],
),
),
),
],
),
);
}),
),
Spacer(),
Obx(
() => controller.questions.length == controller.qnIndex.value
? const RoundedButton(
buttonName: 'Done',
page: '',
)
: Container(),
),
Spacer(),
],
),
),
),
);
}
}
enter code here
I have try to display Selected month data in dropdown selection in flutter , supposed I was select January then it display the January month record in json formate
String monthWiseGraph;
Future<String> getMonthlyGraphData() async {
String url = 'http://example.com/getAgentMonthGraph.php?month='+ monthWiseGraph ;
var response = await http.get(url);
return response.body;
}
Container(
height: 130,
width: 200,
padding: EdgeInsets.only(left: 30, top: 50),
child: Card(
// color: Colors.blueGrey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(20),
bottomLeft: Radius.circular(20)),
side: BorderSide(color: Colors.black)),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.only(top: 10, right: 20, left: 20),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: Text("Monthly",
style:
TextStyle(color: Colors.black, fontSize: 25)),
value: monthWiseGraph,
icon: Icon(Icons.arrow_drop_down),
iconSize: 30,
elevation: 16,
style: TextStyle(color: Colors.black),
onChanged: (String monthNewValue) {
setState(
() {
monthWiseGraph = monthNewValue;
print(monthWiseGraph);
_showMonthlyAlert();
},
);
},
items: <String>[
'January',
'February',
.
.
'December'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(
fontSize: 20,
),
),
);
}).toList(),
),
),
),
],
),
),
),
This is My January data
[
{
userId: "2",
name: "Manish",
total: "32"
},
{
userId: "3",
name: "Altaf",
total: "31"
}
]
This is My February data
[
{
userId: "4",
name: "Prathamesh",
total: "68"
},
{
userId: "7",
name: "Aniket",
total: "62"
},
]
Above image I display the selected month data When I select january from dropdown then it display january data from json like manish and altaf and when I select february it dipslay Prathamesh and Aniket data below is this is normal graph
I am new to flutter
This is my drop down
You have to put "jsonDecode(response.body)" either in a variable or just change the "return" keyword. And then you can access the JSON api because "JsonDecode" will change the JSON data into a Flutter language. Make sure to "import" the file needed.
I created this file json, I fetch the data like "displayName" and "age", also i want see on screen the data from the sublist workout. How can I do and if possibile put this data in a profile page?
this is the Json file i make for my little test db:
[
{
"displayName": "mario",
"age": 27,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Running"
},
{
"nomeworkout": "Brucia Grassi"
}
]
},
{
"displayName": "jessica",
"age": 28,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Spinning"
},
{
"nomeworkout": "Gambe"
}
]
},
{
"displayName": "Pedro",
"age": 29,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Potenziamento"
}
]
}
]
with this page, I created a simple ListView.builder to display the list of items such as "displayName", "age", "weight"; but I didn't understand how to get the data from the internal "workout" list:
import 'dart:convert';
import 'package:fitness_app/trainerPage.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List data;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: FutureBuilder(
future:
DefaultAssetBundle.of(context).loadString('assets/jsonDb.json'),
builder: (context, snapshot) {
var data = JsonDecoder().convert(snapshot.data.toString());
return ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => TrainerPage()));
},
child: Container(
padding: EdgeInsets.all(10),
child: Row(
children: <Widget>[
Text(data[index]['displayName']),
Text(data[index]['age'].toString()),
],
),
),
);
},
);
},
),
),
);
}
}
simple future loader json
Future loadJson()async =>
[
{
"displayName": "mario",
"age": 27,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Running"
},
{
"nomeworkout": "Brucia Grassi"
}
]
},
{
"displayName": "jessica",
"age": 28,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Spinning"
},
{
"nomeworkout": "Gambe"
}
]
},
{
"displayName": "Pedro",
"age": 29,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Potenziamento"
}
]
}
];
simple view
class ContohLoadJson extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: loadJson(),
builder: (context, snapshot){
List data = snapshot.data??[];
return data.isEmpty?Center(child: CircularProgressIndicator(),):
ListView(
children: List.generate(data.length, (index) =>
Card(
child: Container(
padding: EdgeInsets.all(8),
child: Column(
children: [
Row(
children: [
Text("Name : "),
Text(data[index]['displayName'])
],
),
Row(
children: [
Text("Age : "),
Text(data[index]['age'].toString())
],
),
Row(
children: [
Text("Peso : "),
Text(data[index]['peso'].toString())
],
),
Row(
children: [
Text("altezza: "),
Text(data[index]['altezza'].toString())
],
),
Column(
children: List.generate(data[index]['workout'].length, (index2) =>
Card(
child: Container(
padding: EdgeInsets.all(8),
child: Column(
children: [
Row(
children: [
Text("nomeworkout : "),
Text(data[index]['workout'][index2]['nomeworkout'])
],
)
],
),
),
)
).toList(),
)
],
),
),
)
).toList(),
);
},
)
);
}
}
you can extract the list like
var workouts = data[index]['workouts']
then iterate through that list to and render your views
I'm getting my data from here into my fetch datatype
Map fetch = new Map();
eos.Transaction transaction = eos.Transaction()..actions = actions;
_eosClient.pushTransaction(transaction, broadcast: true).then((trx) {
print(trx); //for printing in console
setState(() {
fetch = trx;
});
});
And trying to show this data on my screen
Expanded(
child: new ListView.builder(
itemCount: fetch.length,
itemBuilder: (BuildContext context, int index) {
String key = fetch.keys.elementAt(index);
return Column(
children: <Widget>[
Text(key),
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
'${fetch['processed']['action_traces']}',
),
),
],
);
}),
),
Data in console looks like this and want to print only bold data
processed:{id: 93ae1319f9927becf0c164722fbb58a33518358e9b148f5af92140f6ab01543c, block_num: 51432026, block_time: 2019-09-25T06:21:11.000, producer_block_id: null, receipt: {status: executed, cpu_usage_us: 264, net_usage_words: 13}, elapsed: 264, net_usage: 104, scheduled: false, action_traces: [{action_ordinal: 1, creator_action_ordinal: 0, closest_unnotified_ancestor_action_ordinal: 0, receipt: {receiver: guru11111111, act_digest: 55e9b8f98bde721c3f3e53cf98a20814a5d426290b0bf55f842d97866bc71f6c, global_sequence: 488625827, recv_sequence: 353, auth_sequence: [[guru11111111, 423]], code_sequence: 25, abi_sequence: 14}, receiver: guru11111111, act: {account: guru11111111, name: getborrower, authorization: [{actor: guru11111111, permission: active}], data: {acc_name: guru}, hex_data: 0000000000a0af66}, context_free: false, elapsed: 69, console: Borrower Name: guru ID: 1 Location: varanasi Phone Number: 8563070443 Loan amount: 4652007308841189376, trx_id: 93ae1319f9927becf0c164722fbb58a33518358e9b148f
I have tried to make it look like this
{
transaction_id: c459d2da5100afb1b4ab0352debfa4736aadd8c2e36529fe0861c9c8cadddeae,
processed: {
id: c459d2da5100afb1b4ab0352debfa4736aadd8c2e36529fe0861c9c8cadddeae,
block_num: 51299894,
block_time: 2019-09-24T11:40:11.500,
producer_block_id: null,
receipt: {
status: executed,
cpu_usage_us: 226,
net_usage_words: 13
},
elapsed: 226,
net_usage: 104,
scheduled: false,
action_traces: [
{
action_ordinal: 1,
creator_action_ordinal: 0,
closest_unnotified_ancestor_action_ordinal: 0,
receipt: {
receiver: guru11111111,
act_digest: 55e9b8f98bde721c3f3e53cf98a20814a5d426290b0bf55f842d97866bc71f6c,
global_sequence: 488304782,
recv_sequence: 329,
auth_sequence: [
[guru11111111, 399]
],
code_sequence: 25,
abi_sequence: 14
},
receiver: guru11111111,
act: {
account: guru11111111,
name: getborrower,
authorization: [
{
actor: guru11111111,
permission: active
}
],
data:
{
acc_name: guru
},
hex_data: 0000000000a0af66
},
context_free: false,
elapsed: 60,
console:
Borrower Name: guru
ID: 1
Location: varanasi
Phone Number: 8563070443,
Loan Amount:465200
}
Text('${fetch['processed']['action_traces']}'),
I'm able to print till 'action_traces' but can not print inside 'action_traces'
after action_traces there is a array so i have given the index of array,
we can also use foreach loop for this.
//Text('${fetch['processed']['action_traces'][0]['console']}',)
Expanded(
child: ListView.builder(
itemCount: fetch.length,
itemBuilder: (BuildContext context, int index) {
// String key = fetch.keys.elementAt(index);
print('${fetch[fetch.keys.elementAt(index)]}');
return Center(
child: Text(
'${fetch['processed']['action_traces'][0]['console']}',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
);
}),
)
Firstly you will need to create proper model for parsing this JSON and for that you can use Dart's official package json_annotation. After you have created model classes you will need to desrialise the json into Dart model and then use them as you want in your code.
So I have a listview.builder in my Project management app in Flutter. This listview is filled with tasks(they can be: new, started, done). I get this data from an API and want the ones that are "new" to appear at the top, the ones that are started to be in the middle and the bottom for the "done" ones! - This is how it looks right now
This is my Class, notice that I get the state from the API/JSON
class ProjectTask {
final int id;
final String description;
final String state;
final List assigned_users;
final List subtasks;
ProjectTask(this.id,
this.description,
this.state,
this.assigned_users,
this.subtasks);
}
The ListView
else return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
if(snapshot.data[index].state == "done") {
return Slidable(
//SLIDABLE STUFF
delegate: SlidableStrechDelegate(),
actionExtentRatio: 0.25,
actions: <Widget>[
//ACTION ONE
IconSlideAction(
caption: ("Information"),
foregroundColor: Colors.white,
color: Colors.black38,
icon: Icons.info,
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>projectTask(snapshot.data[index])));
},
),
],
child: ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => projectTask(
snapshot.data[index],
)));
},
title: Text("${snapshot.data[index].description[0].toString().toUpperCase()}"
"${snapshot.data[index].description.toString().substring(1)}", maxLines: 1, style: TextStyle(
color: Colors.black87, fontSize: 17)
),
subtitle: Text("done"),
leading: Icon(Icons.check_circle, color: Colors.green),
trailing: Icon(Icons.arrow_right, color: Colors.black54,),
),
);
}
else if(snapshot.data[index].state == "started") {
return Slidable(
//SLIDABLE STUFF
delegate: SlidableStrechDelegate(),
actionExtentRatio: 0.25,
actions: <Widget>[
//ACTION ONE
IconSlideAction(
caption: ("Information"),
foregroundColor: Colors.white,
color: Colors.black38,
icon: Icons.info,
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>projectTask(snapshot.data[index])));
},
),
],
secondaryActions: <Widget>[
//ACTION TWO
IconSlideAction(
caption: ("Complete Me"),
color: Colors.green,
icon: Icons.radio_button_checked,
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>projectTask(snapshot.data[index])));
},
)
],
child: ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => projectTask(
snapshot.data[index],
)));
},
title: Text("${snapshot.data[index].description[0].toString().toUpperCase()}"
"${snapshot.data[index].description.toString().substring(1)}", maxLines: 1, style: TextStyle(
color: Colors.black87, fontSize: 17)
),
subtitle: Text("working"),
leading: Icon(Icons.radio_button_checked, color: Colors.blue),
trailing: Icon(Icons.arrow_right, color: Colors.black54,),
),
);
}
else {
return Slidable(
//SLIDABLE STUFF
delegate: SlidableStrechDelegate(),
actionExtentRatio: 0.25,
actions: <Widget>[
//ACTION ONE
IconSlideAction(
caption: ("Information"),
foregroundColor: Colors.white,
color: Colors.black38,
icon: Icons.info,
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>projectTask(snapshot.data[index])));
},
),
],
secondaryActions: <Widget>[
//ACTION TWO
IconSlideAction(
caption: ("Start Work"),
color: Colors.blue,
icon: Icons.radio_button_checked,
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>projectTask(snapshot.data[index])));
},
)
],
//LISTTILE
child: ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => projectTask(
snapshot.data[index],
)));
},
title: Text("${snapshot.data[index].description[0].toString().toUpperCase()}"
"${snapshot.data[index].description.toString().substring(1)}", maxLines: 1, style: TextStyle(
color: Colors.black87, fontSize: 17)
),
subtitle: Text("new"),
leading: Icon(Icons.radio_button_checked, color: Colors.red),
trailing: Icon(Icons.arrow_right, color: Colors.black54,),
),
);
}
}
);
JSON
[
{
"id": 7,
"description": "Finishedddddd",
"state": "done",
"assigned_users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
}
],
"subtasks": []
},
{
"id": 9,
"description": "Newwww task for Huuugo",
"state": "started",
"assigned_users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
}
],
"subtasks": []
},
{
"id": 11,
"description": "Google presentation om IKEAS ekonomi",
"state": "done",
"assigned_users": [
{
"username": "studentone",
"fullname": "Student One"
}
],
"subtasks": []
},
{
"id": 15,
"description": "entail",
"state": "new",
"assigned_users": [],
"subtasks": [
{
"id": 1,
"description": "dasdasdasd"
},
{
"id": 2,
"description": "fsdfsdfsdf"
}
]
},
{
"id": 17,
"description": "gmmgmsgd",
"state": "new",
"assigned_users": [],
"subtasks": []
},
{
"id": 18,
"description": "dasd",
"state": "started",
"assigned_users": [],
"subtasks": []
},
{
"id": 19,
"description": "fsdfdsfsd",
"state": "started",
"assigned_users": [],
"subtasks": []
},
{
"id": 20,
"description": "Werner",
"state": "new",
"assigned_users": [],
"subtasks": []
},
{
"id": 21,
"description": "teadfsd",
"state": "done",
"assigned_users": [],
"subtasks": []
},
{
"id": 22,
"description": "task",
"state": "new",
"assigned_users": [],
"subtasks": []
},
{
"id": 23,
"description": "asdasd",
"state": "started",
"assigned_users": [],
"subtasks": []
},
{
"id": 24,
"description": "asdasd",
"state": "new",
"assigned_users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
}
],
"subtasks": []
}
]
You should sort the data before creating the ListView. You can use basic dart sort method. Basically you just need to implement the compare function which returns an integer that the sign of the return value specify items order.
Read this example code for better understanding:
enum TaskState {
newTask, done, started
}
class Task {
Task(this.id, this.state);
final int id;
final TaskState state;
String toString() {
return "$id";
}
}
int compare(TaskState a, TaskState b) {
if (a == b) return 0;
switch(a) {
case TaskState.newTask:
return -1;
break;
case TaskState.started:
if(b == TaskState.newTask) return 1;
return -1;
break;
case TaskState.done:
return 1;
break;
}
}
void main() {
List<Task> list = [
Task(1, TaskState.done),
Task(3, TaskState.newTask),
Task(4, TaskState.started),
Task(2, TaskState.done),
Task(10, TaskState.newTask),
];
list.sort((a, b) => compare(a.state, b.state));
print(list);
}
Implementing in your code should be something like this
FutureBuilder<List<ProjectTask>>(
future: someQuery(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snap) {
snap.data.sort((a, b) => {
if (a == b) return 0;
switch(a) {
case "new":
return -1;
break;
case "started":
if(b == "new") return 1;
return -1;
break;
case "done":
return 1;
break;
}
});
return ListView.builder(
...
)
}
)
I found this helpful article with a great example to sort a list of objects by any field: https://www.kindacode.com/article/sorting-lists-in-dart/
Example:
class User {
String name;
int age;
User(this.name, this.age);
#override
toString() {
return ('$name - $age years old \n');
}
}
void main() {
List<User> users = [
User('Plumber', 10),
User('John Doe', 50),
User('Pipi', 4),
User('Invisible Man', 31),
User('Electric Man', 34)
];
// Age from small to large
users.sort((a, b) => a.age.compareTo(b.age));
print('Age ascending order: ${users.toString()}');
// Age from large to small
users.sort((a, b) => b.age.compareTo(a.age));
print('Age descending order: ${users.toString()}');
}