'get Results from all toggle switches that are dynamically created from a list and return as json to send via HTTP
first of all I am new to flutter and am learning. I have a List that is created from a json call, this includes the question and a ToggleSwitch to select either yes or no. I want to return a list of Json from this. my problem is that i can return one result at a time and have no idea how to return all the results as a Json string such as
[
{
"question_id": "6",
"question_answer": "0"
},
{
"question_id": "7",
"question_answer": "1"
},
{
"question_id": "8",
"question_answer": "0"
},
{
"question_id": "9",
"question_answer": "1"
},
{
"question_id": "10",
"question_answer": "1"
}
]
please remember that this list is created dynamically and can grow to any length.
I will then take all these results and send them to a SQLLite Db to store until I send the data via HTTP.
Any help will be greatly appreciated as I do not understand the Demos that im finding.
Full code below
import 'package:flutter/material.dart';
import 'package:reception/right_of_admission.dart';
import 'activate_boom.dart';
import 'camera/camera.dart';
import 'capture_assets.dart';
import 'capture_visitor_card.dart';
import 'covid.dart';
import 'db_helper.dart';
import 'show_dest.dart';
import 'visitor_details.dart';
import 'dart:async';
import 'dart:convert';
import 'package:device_info/device_info.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:reception/visitor_details.dart';
import 'package:reception/settings.dart';
import 'package:reception/utils.dart';
import 'package:reception/db_helper.dart';
import 'dart:io' show Directory, File, HttpHeaders, Platform;
import 'package:toggle_switch/toggle_switch.dart';
String dbUserId = "";
String dbSiteId = "";
String dbDeviceId = "";
String answers = "";
var res = '';
bool _switchValue = true;
Future<void> _deviceDetails() async {
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
try {
if (Platform.isAndroid) {
var build = await deviceInfoPlugin.androidInfo;
identifier = build.androidId;
//UUID for Android
} else if (Platform.isIOS) {
var data = await deviceInfoPlugin.iosInfo;
identifier = data.identifierForVendor;
}
} on PlatformException {
print('Failed to get platform version');
}
}
//get details from Local Database
nextPage(context) async {
final data = await SQLHelper.getMatrixItems();
if (data[0]['lDestination'].toString() == "0") {
print('Destination Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page3()));
} else if (data[0]['lPicture'].toString() == "0") {
print('Picture Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page4()));
} else if (data[0]['lVisitorDetails'].toString() == "0") {
print('Visitor Details Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page5()));
} else if (data[0]['lAssets'].toString() == "0") {
print('Assets Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page6()));
} else if (data[0]['lCovid'].toString() == "0") {
print('Covid Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page7()));
} else if (data[0]['lRights'].toString() == "0") {
print('Right Of Admission Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page8()));
} else if (data[0]['lBoom'].toString() == "0") {
print('Boom Not Empty');
Navigator.push(context, MaterialPageRoute(builder: (context) => Page9()));
} else {
print('No Matrix');
Navigator.push(
context, MaterialPageRoute(builder: (context) => const Page1()));
}
}
class Page2 extends StatefulWidget {
@override
State<Page2> createState() => _Page2State();
}
class _Page2State extends State<Page2> {
List<QuestionCard> list = List<int>.empty().cast<QuestionCard>();
void initState() {
super.initState();
_getDetails(context);
}
var isLoading = false;
int myActive = 3;
int latchVal = 0;
int myLatch = 0;
int pushVal = 0;
int myPush = 0;
bool isSwitched = false;
Widget build(BuildContext context) {
return MaterialApp(
title: 'Page2',
home: Scaffold(
appBar: AppBar(
title: const Center(
child: Text('Page2'),
),
),
body: isLoading
? const Center(
child: CircularProgressIndicator(),
)
: Center(
child: Column(children: <Widget>[
const SizedBox(
height: 10.0,
),
Container(
padding: const EdgeInsets.all(0.0),
width: 500.0,
height: 350.0,
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent)),
child: ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
child: InkWell(
child: Card(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10.0),
side: BorderSide(
color: Colors.blue.withOpacity(0.1),
width: 0.5,
),
),
color: Colors.grey[200],
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment
.start,
children: <Widget>[
Text(
list[index].question_id,
overflow: TextOverflow
.ellipsis,
style: const TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight:
FontWeight.bold,
height: 1.5),
),
Text(
list[index]
.question_question,
overflow: TextOverflow
.ellipsis,
style: const TextStyle(
color: Colors.black,
fontSize: 15,
height: 1.5),
),
Transform.scale(
scale: 1,
child: ToggleSwitch(
minWidth: 100.0,
initialLabelIndex:
myPush,
inactiveBgColor:
Colors.grey,
activeBgColors: [
[Colors.blue],
[Colors.red]
],
inactiveFgColor:
Colors.white,
totalSwitches: 2,
labels: ['No', 'Yes'],
onToggle: (value) {
print(
'switched to: $value');
pushVal = value!;
},
),
),
]),
)
],
)))));
},
)),
ElevatedButton(
child: const Text('Next'),
onPressed: () {
nextPage(context);
},
),
])),
));
}
Future<void> _getDetails(BuildContext context) async {
await _deviceDetails();
final data = await SQLHelper.getItems();
String userId = data[0]['userId'];
String siteId = data[0]['siteId'];
String deviceId = data[0]['deviceId'];
dbUserId = userId;
dbSiteId = siteId;
dbDeviceId = deviceId;
print("This is a userId: " + userId);
print("This is a siteId: " + siteId);
print("This is a deviceId: " + deviceId);
// print("new: " + identifier);
fetchQuestionsFromServer(context);
}
Future<void> fetchQuestionsFromServer(context) async {
var headers = {
'Authorization': '',
'Content-Type': 'application/json'
};
setState(() {
isLoading = true;
print('isloading True');
});
var request = http.Request('GET', Uri.parse(getQuestions));
request.body = json.encode(
{"deviceId": dbDeviceId, "userId": dbUserId, "siteId": dbSiteId});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
print(dbUserId);
print(dbUserId);
print(dbDeviceId);
if (response.statusCode == 200) {
final questions = await response.stream.bytesToString();
list = (json.decode(questions) as List)
.map((data) => QuestionCard.fromJson(data))
.toList();
setState(() {
isLoading = false;
print('isloading false');
});
print(questions);
print(list);
// await SQLHelper.deleteMatrixItem();
//Add item to local DB
// await SQLHelper.createMatrixItem(boom, covid, assets, visitorDevice,
// picture, destinations, questions, visitor, rights);
// print(matrixDecoded);
} else {
print(response.reasonPhrase);
}
}
}
class QuestionCard {
final String question_id;
final String question_question;
QuestionCard({
required this.question_id,
required this.question_question,
});
factory QuestionCard.fromJson(Map<String, dynamic> json) {
return QuestionCard(
question_id: json['question_id'] as String,
question_question: json['question_question'] as String,
);
}
}
class Answers {
String question_id;
int question_value;
Answers(this.question_id, this.question_value);
Map toJson() => {
'question_id': question_id,
'question_value': question_value,
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
