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'].
Related
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
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.
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
I am trying to convert a list of type Response to a json, but I am not getting it.
This is my list of objects:
I want a json like this:
{
"preguntas": [
{
"id": "7d0e0584-3049-4814-b127-0faa02b455b4",
"encuesta": null,
"orden": 1,
"descripcion": "Dificultad para respirar de moderada a grave (no puede decir frases completas)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
},
{
"id": "9809e985-2d1f-4f79-a5b9-da6731e14012",
"encuesta": null,
"orden": 2,
"descripcion": "Fiebre o sentirse afiebrados (escalofríos, sudoración)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
}
]
}
I'm new to Flutter, please if someone help me, I really appreciate it.
You can can copy paste run full code below
You can use full model class definition Payload below and parse with payloadToJson
This example code create Payload object with your json string and convert it back to json string
code snippet
String payloadToJson(Payload data) => json.encode(data.toJson());
...
String str = payloadToJson(payload);
print(str);
output
{"preguntas":[{"id":"7d0e0584-3049-4814-b127-0faa02b455b4","encuesta":null,"orden":1,"descripcion":"Dificultad para respirar de moderada a grave (no puede decir frases completas)","respuestas":[],"obligatoria":true,"estado":false,"fechaCreacion":null,"responsableCreacion":null,"fechaModificacion":null,"responsableModificacion":null},{"id":"9809e985-2d1f-4f79-a5b9-da6731e14012","encuesta":null,"orden":2,"descripcion":"Fiebre o sentirse afiebrados (escalofríos, sudoración)","respuestas":[],"obligatoria":true,"estado":false,"fechaCreacion":null,"responsableCreacion":null,"fechaModificacion":null,"responsableModificacion":null}]}
full code
import 'package:flutter/material.dart';
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Pregunta> preguntas;
Payload({
this.preguntas,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
preguntas: List<Pregunta>.from(json["preguntas"].map((x) => Pregunta.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"preguntas": List<dynamic>.from(preguntas.map((x) => x.toJson())),
};
}
class Pregunta {
String id;
dynamic encuesta;
int orden;
String descripcion;
List<dynamic> respuestas;
bool obligatoria;
bool estado;
dynamic fechaCreacion;
dynamic responsableCreacion;
dynamic fechaModificacion;
dynamic responsableModificacion;
Pregunta({
this.id,
this.encuesta,
this.orden,
this.descripcion,
this.respuestas,
this.obligatoria,
this.estado,
this.fechaCreacion,
this.responsableCreacion,
this.fechaModificacion,
this.responsableModificacion,
});
factory Pregunta.fromJson(Map<String, dynamic> json) => Pregunta(
id: json["id"],
encuesta: json["encuesta"],
orden: json["orden"],
descripcion: json["descripcion"],
respuestas: List<dynamic>.from(json["respuestas"].map((x) => x)),
obligatoria: json["obligatoria"],
estado: json["estado"],
fechaCreacion: json["fechaCreacion"],
responsableCreacion: json["responsableCreacion"],
fechaModificacion: json["fechaModificacion"],
responsableModificacion: json["responsableModificacion"],
);
Map<String, dynamic> toJson() => {
"id": id,
"encuesta": encuesta,
"orden": orden,
"descripcion": descripcion,
"respuestas": List<dynamic>.from(respuestas.map((x) => x)),
"obligatoria": obligatoria,
"estado": estado,
"fechaCreacion": fechaCreacion,
"responsableCreacion": responsableCreacion,
"fechaModificacion": fechaModificacion,
"responsableModificacion": responsableModificacion,
};
}
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> {
int _counter = 0;
void _incrementCounter() {
String jsonString = '''
{
"preguntas": [
{
"id": "7d0e0584-3049-4814-b127-0faa02b455b4",
"encuesta": null,
"orden": 1,
"descripcion": "Dificultad para respirar de moderada a grave (no puede decir frases completas)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
},
{
"id": "9809e985-2d1f-4f79-a5b9-da6731e14012",
"encuesta": null,
"orden": 2,
"descripcion": "Fiebre o sentirse afiebrados (escalofríos, sudoración)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
}
]
}
''';
Payload payload = payloadFromJson(jsonString);
String str = payloadToJson(payload);
print(str);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Maybe it can works; I can create Model class for example. You should add toJson() Function to your Class.
class Model{
String id = "7d0e0584-3049-4814-b127-0faa02b455b4";
String encuesta = "null";
int orden = 1;
String description = "Dificultad para respirar de moderada a grave (no puede...)";
bool obligatoria = true;
//Model(bla bla bla....)
Model();
toJson(){
return {
"id":id,
"encuesta":encuesta,
"orden":orden,
"description":description,
"obligatoria":obligatoria
};
}
}
void main() {
Map<String,List<dynamic>> jsonMap = new Map();
List<dynamic> list = new List();
for(int i = 0 ; i < 3;i++){
Model model = new Model();
list.add(model.toJson());
}
jsonMap['preguntas'] = list;
print(jsonMap);
}
Result (Print):
{
preguntas: [
{
id: 7d0e0584-3049-4814-b127-0faa02b455b4,
encuesta: null,
orden: 1,
description: Dificultadpararespirardemoderadaagrave(nopuede...),
obligatoria: true
},
{
id: 7d0e0584-3049-4814-b127-0faa02b455b4,
encuesta: null,
orden: 1,
description: Dificultadpararespirardemoderadaagrave(nopuede...),
obligatoria: true
},
{
id: 7d0e0584-3049-4814-b127-0faa02b455b4,
encuesta: null,
orden: 1,
description: Dificultadpararespirardemoderadaagrave(nopuede...),
obligatoria: true
}
]
}
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.