How to sort the array randomly in MongoDB? - mongodb

I want to get random question from the list,
and i want to sort randomly the option,
i tried and i get the random question, but i don`t know how to sort randomly from the array.
this is my sample
{ 'question': 'question 1...', 'option': [{ 'id': '1', 'text': 'opt1' }, { 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }] },
{ 'question': 'question 2...', 'option': [{ 'id': '1', 'text': 'opt1' }, { 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }, { 'id': '4', 'text': 'opt4' }, { 'id': '5', 'text': 'opt5' }] },
{ 'question': 'question 3...', 'option': [{ 'id': '1', 'text': 'opt1' }, { 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }] },
{ 'question': 'question 4...', 'option': [{ 'id': '1', 'text': 'opt1' }, { 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }, { 'id': '4', 'text': 'opt4' }] },
{ 'question': 'question 5...', 'option': [{ 'id': '1', 'text': 'opt1' }, { 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }] },
db.getCollection('collection').aggregate([
{
"$sample": { "size": 3 }
},
{
"$addFields": {
"option_count": {"$size": "$option"}
},
}
])
i want to get this result
{ 'question': 'question 2...', 'option': [{ 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }, { 'id': '1', 'text': 'opt1' }, { 'id': '5', 'text': 'opt5' }, { 'id': '4', 'text': 'opt4' }] },
{ 'question': 'question 5...', 'option': [{ 'id': '3', 'text': 'opt3' }, { 'id': '1', 'text': 'opt1' }, { 'id': '2', 'text': 'opt2' } ] },
{ 'question': 'question 4...', 'option': [{ 'id': '2', 'text': 'opt2' }, { 'id': '3', 'text': 'opt3' }, { 'id': '1', 'text': 'opt1' }, { 'id': '4', 'text': 'opt4' }] },

Use $function New in version 4.4.
shuffle
db.collection.aggregate([
{
"$sample": {
"size": 3
}
},
{
"$set": {
"option": {
"$function": {
"body": "function (arr) {return arr.sort( () => Math.random()-0.5) ;}",
"args": [
"$option"
],
"lang": "js"
}
}
}
}
])
mongoplayground

Related

Showing the dropdown list with special List and Multiple Dynamic Dependent Dropdown List

List<Map<String, dynamic>> category123 = [
{
"name": "Python",
"department": "second-choice",
"detail": ['11', '12', '13', '14'],
},
{
"name": "Javascript",
"department": "first-choice",
"detail": ['21', '22', '23', '24'],
},
{
"name": "PHP",
"department": "first-choice",
"detail": ['31', '32', '33', '34'],
},
{
"name": "C#",
"department": "second-choice",
"detail": ['41', '42', '43', '44'],
},
{
"name": "Java",
"department": "first-choice",
"detail": ['51', '52', '53', '54'],
},
{
"name": "C++",
"department": "second-choice",
"detail": ['61', '62', '63', '64'],
},
{
"name": "Erlang",
"department": "first-choice",
"detail": ['71', '72', '73', '74'],
},
];
Is it possibly make this List become like picture result? and I also want the detail (list) will be display in other list based on the which "name" is selected.
For the dependents, if i select the JavaScript in selection, in another dropdown list should show the detail List of the Javascript including 11, 12, 13, 14
Take a look at this:
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Map<String, dynamic>> category123 = [
{
"name": "Python",
"department": "second-choice",
"detail": ['11', '12', '13', '14'],
},
{
"name": "Javascript",
"department": "first-choice",
"detail": ['21', '22', '23', '24'],
},
{
"name": "PHP",
"department": "first-choice",
"detail": ['31', '32', '33', '34'],
},
{
"name": "C#",
"department": "second-choice",
"detail": ['41', '42', '43', '44'],
},
{
"name": "Java",
"department": "first-choice",
"detail": ['51', '52', '53', '54'],
},
{
"name": "C++",
"department": "second-choice",
"detail": ['61', '62', '63', '64'],
},
{
"name": "Erlang",
"department": "first-choice",
"detail": ['71', '72', '73', '74'],
},
];
late final List data;
dynamic selectedItem;
String? selectedDetail;
#override
void initState() {
final groups = groupBy(category123, (Map e) => e['department']);
data = [
for (final item in groups.entries)
for (final value in [item.key, ...item.value])
if (value is Map)
{'value': value, 'bold': false}
else
{'value': value, 'bold': true}
];
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
children: [
DropdownButton<dynamic>(
value: selectedItem,
items: [
for (final item in data)
item['bold'] == true
? DropdownMenuItem(
enabled: false,
child: Text(item['value'],
style:
const TextStyle(fontWeight: FontWeight.bold)))
: DropdownMenuItem(
value: item['value'],
child: Padding(
padding: const EdgeInsets.only(left: 8),
child: Text(item['value']['name']),
))
],
onChanged: (value) {
setState(() {
selectedItem = value;
});
}),
if (selectedItem != null)
DropdownButton<String>(
value: selectedItem['detail'].contains(selectedDetail)
? selectedDetail
: null,
items: [
for (final item in selectedItem['detail'])
DropdownMenuItem(value: item, child: Text(item))
],
onChanged: (value) {
setState(() {
selectedDetail = value;
});
})
],
))));
}
}

How to add a label inside the dropdown item with list inside the list (FLUTTER)

List<Map<String, dynamic>> category = [
{
"name": "One",
"detail": ['1', '1', '1', '1', '1', '1']
},
{
"name": "two",
"detail": ['2', '2', '2', '2', '2', '2']
},
{
"name": "three",
"detail": ['3', '3', '3', '3', '3', '3']
},
];
I want to add the name as the label in dropdown item, and the detail as the item. For example, as showing in the picture
The bold text should be the "name", the normal text will be the detail items
This can give you an idea of how to possibly do it:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<Map<String, dynamic>> category = [
{
"name": "One",
"detail": ['11', '12', '13', '14']
},
{
"name": "two",
"detail": ['21', '22', '23', '24']
},
{
"name": "three",
"detail": ['31', '32', '33', '34']
},
];
late final List data;
String? selectedItem;
#override
void initState() {
data = [
for (final item in category)
for (final value in item.values)
if (value is List)
for (final listValue in value) {'value': listValue, 'bold': false}
else
{'value': value, 'bold': true}
];
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButton<String>(
value: selectedItem,
items: [
for (final item in data)
item['bold'] == true
? DropdownMenuItem(
enabled: false,
child: Text(item['value'],
style: const TextStyle(
fontWeight: FontWeight.bold)))
: DropdownMenuItem(
value: item['value'],
child: Padding(
padding: const EdgeInsets.only(left: 8),
child: Text(item['value']),
))
],
onChanged: (value) {
setState(() {
selectedItem = value;
});
}))));
}
}
Output:
In the initState I transform the data in a way so you have a list where each item corresponds to a dropdown item. With additional info whether it should be bold or not

How to get particular value from Dropdown list in Flutter | Dart

I have a list of items that were received from API. I want to print a particular value of that selected item from the list. The list is,
[
{
'id': '1',
'name': 'roy',
'designation': 'engineer',
},
{
'id': '2',
'name': 'john',
'designation': 'doctor',
},
{
'id': '3',
'name': 'rose',
'designation': 'clerk',
}
];
From this list, if I select john from the dropdown menu then it should print the designation in the console. If I select rose then it prints clerk in the console. How to achieve this. Below is my code,
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
#override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
List users = [
{
'id': '1',
'name': 'roy',
'designation': 'engineer',
},
{
'id': '2',
'name': 'john',
'designation': 'doctor',
},
{
'id': '3',
'name': 'rose',
'designation': 'clerk',
}
];
String? userId;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: true,
hint: const Padding(
padding: EdgeInsets.all(8.0),
child: Text('Select Item'),
),
value: userId,
items: users.map((item) {
return DropdownMenuItem(
child: Text(item['name']),
value: item['id'].toString(),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
userId = newValue;
});
},
),
),
),
);
}
}
What code I need to add inside onChanged function to get designation of that selected user.

FLUTTER: The method 'map' was called on null

the problem is in this line:
...(mapsystem[perguntaid]['respostas'] as List<String>)
.map((resposta) {
return Resposta(respondendo, resposta);
}).toList()
"Resposta" is a widget in other file that returns a raised button, but this is not the problem
Also, it gaves no errors in problems output, just in the emulator when i run the app
import 'package:flutter/material.dart';
import './pergunta.dart';
import './resposta.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return AppState();
}
}
class AppState extends State<App> {
double score = 0;
var perguntaid = 0;
void respondendo() {
setState(() {
perguntaid = perguntaid + 1;
});
score = score + 0.5;
print(score);
}
#override
Widget build(BuildContext context) {
var mapsystem = [
{
'Tema': 'Memória',
'repostas': [
'Não há perda de memória óbvia. Apenas alguns esquecimentos que não fazem diferença',
'Esquecimento leve e regular de eventos (Esquece compromissos, repete perguntas, etc)',
'Perda de memória de leve a moderada, esquece de eventos recentes, o que atrapalha atividades diárias',
'Perda de memória moderada a severa, informações recentes são rapidamente esquecidas e lembra custa um significante esforço',
'Perda de memória severa, quase impossível lembrar novas informações, e memórias passadas podem estar afetadas'
],
},
{
'Tema': 'Orientação',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Tomada de decisões e resolução de problemas',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Atividades fora de casa',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Habilidades em casa e Hobbies',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Hábitos de Higiene pessoal',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Mudanças de comportameto e personalidade',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Habilidades de linguagem e comunicação',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Humor',
'repostas': ['1', '2', '3', '4', '5'],
},
{
'Tema': 'Atenção e Concentração',
'repostas': ['1', '2', '3', '4', '5'],
},
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text('Memory Mate'),
),
body: Column(
children: [
Pergunta(
mapsystem[perguntaid]['Tema'],
),
...(mapsystem[perguntaid]['respostas'] as List<String>)
.map((resposta) {
return Resposta(respondendo, resposta);
}).toList()
],
),
),
);
}
}
here is a picture of the error in screen:
link to the image
In your data, you have the key repostas, while on the error line you write respostas with an extra "s". Just change to mapsystem[perguntaid]['repostas'].

Changing Screen when Floating Action Button is pressed for the last time

Each time the Floating Action Button is pressed the nextExercise() is called. There I managed to update the Ex Map and go the next one.
Starting from 'ex1' to 'ex2' etc.
When I reach the 'ex9' (last page) I would like to change a screen because the exercises will have been completed.
I tried a lot of things. Also tried the suggestions from the answers but I can not find the solution, please help!
New Code below:
class DynamicWorkoutStart extends StatefulWidget {
#override
_DynamicWorkoutStartState createState() => _DynamicWorkoutStartState();
}
class _DynamicWorkoutStartState extends State<DynamicWorkoutStart> {
VideoPlayerController _videoPlayerController1;
ChewieController _chewieController;
var ex = {
'ex1': {
'title': 'HIGH-KNEE SKIP',
'videoNr': '1',
'description1': '- Heel should not touch the ground',
'description2': ''
},
'ex2': {
'title': 'OVER-UNDERS',
'videoNr': '2',
'description1': '- Flip your Hips!',
'description2': ''
},
'ex3': {
'title': 'WALKING HAMSTRING',
'videoNr': '3',
'description1': '- Point your Toe upwards the Head.',
'description2': '- Keep you back flat!'
},
'ex4': {
'title': 'QUAD STRETCH WITH LEAN',
'videoNr': '4',
'description1': '- Keep your Abs tight.',
'description2': ''
},
'ex5': {
'title': 'FRANKENSTEIN KICKS',
'videoNr': '5',
'description1': '- Keep your Knee straight.',
'description2': ''
},
'ex6': {
'title': 'ADDUCTOR STRETCH',
'videoNr': '6',
'description1': '- Keep your back straight.',
'description2': ''
},
'ex7': {
'title': 'HIPFLEXOR STRETCH',
'videoNr': '7',
'description1': '- Rotate towrds lead leg.',
'description2': '- Keep your Hips straight.'
},
'ex8': {
'title': 'HIGH SKIP INTO DEEP SQUAT',
'videoNr': '8',
'description1': '- 3 high Skips and then Deep Squat.',
'description2': '- Get your food over the fence.'
},
'ex9': {
'title': 'QUICKLINE INTO STICK',
'videoNr': '9',
'description1': '- Go over the line as fast as you can!',
'description2': '- 30sec x 3 sets per leg.'
},
};
#override
void initState() {
super.initState();
_videoPlayerController1 = VideoPlayerController.asset(
'assets/videos/${ex['ex1']['videoNr']}.m4v');
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController1,
aspectRatio: 16 / 9,
showControls: false,
autoPlay: true,
looping: true,
);
}
#override
void dispose() {
_videoPlayerController1.dispose();
_chewieController.dispose();
super.dispose();
}
nextExercise(BuildContext context) {
int _curr;
int _next;
setState(() {
for (_curr = 1; _curr <= 8; _curr++) {
_next = _curr + 1;
if (ex['ex$_curr'] != null) {
ex['ex$_curr'] = ex['ex$_next'];
}
}
if (_curr >= 9) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FinishDynamicWorkout(),
),
);
}
_chewieController.dispose();
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController1 =
VideoPlayerController.asset(
'assets/videos/${ex['ex1']['videoNr']}.m4v'),
aspectRatio: 16 / 9,
showControls: false,
autoPlay: true,
looping: true,
);
});
}
setState() is used to set the screen state which ultimately updates the widget. You'll have to take out the screen navigation outside setState().
Besides, nextExcercise() doesn't have 'context'. You'll have to pass the context from the Widget build method. Example from this page :
class FirstRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Route'),
),
body: Center(
child: RaisedButton(
child: Text('Open route'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
),
);
}
}
Over here, the Navigator.push has the context from the (main) build method.