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 some local JSON data that I've parsed into my app. The data contains a few arrays and math questions (building a quiz app), so based on the math there are chapters which I've displayed in a ListView builder, when clicking on one of those it opens a new screen and passes on specific data for that chapter based on the index of the chapter.
In my quiz screen math questions in an array are brought from the JSON data depending on what chapter it is, I have the questions shuffled so that they appear in a random order, issue is when a user tries to answer a question in a provided TextField the keyboard opens as intended but the state of the UI changes which also changes the currently displayed question. How can I stop this?
To see the problem I have in the app here's a video link: https://youtu.be/n_VeT26I8NE
The JSON data has been parsed from a different screen and set in these variables:
List quiz = widget.newData["quiz"];
//Shuffle questions
var randomQuiz = (quiz..shuffle()).first;
If you prefer to read the Dart code from GitHub: https://github.com/BotsheloRamela/classio/blob/main/quiz_screen.dart
Some of the JSON data:
[
{
"chapter": "Exponents & Surds",
"introduction": {
"description": "A number's exponent determines how many times to multiply it.
Exponents can also be called powers or indices. In mathematics, a surd is a value
that cannot be further simplified into a whole number or integer. They are
irrational numbers.",
"videoID": ["568dGLFTom8", "XZRQhkii0h0"]
},
"quiz": [
{
"question": "Simplify the follwoing.",
"sum": "2a^2.3a^2.b^0",
"answer": "6a^5",
"explaination": ""
},
{
"question": "Rewrite the following with prime bases, your answer should be a fraction.",
"sum": "16.8^{-4}",
"answer": "1/256",
"explaination": ""
},
{
"question": "Solve the following, your answer should be a fraction.",
"sum": "\\frac{(-3a^3 b)^2}{a^5 b^3}",
"answer": "9a/b",
"explaination": ""
},
{
"question": "Rewrite the following with prime bases and simplify, your answer should be a fraction.",
"sum": "(\\frac{2x^3}{8y^{-4}})^{-3}",
"answer": "\\frac{64}{x^9 y^12}",
"explaination": ""
}
]
},
{
"chapter": "Equations & Inequalities",
"introduction": {
"description": "Equations and inequalities are both mathematical sentences made up of two expressions related to one another. The symbol = indicates that two expressions are regarded as equal within an equation. While in an inequality, two terms are not necessarily equal, which is indicated by the following symbols: >, <, ≤ or ≥.",
"videoID": ["hJ-_OoCHTks"]
},
"quiz": [
{
"question": "Show that the following trinomial is a perfect square.",
"sum": "x^2+2x+1",
"answer": "(x+1)^2",
"explaination": ""
},
{
"question": "Show that the following trinomial is a perfect square.",
"sum": "x^2-6x+9",
"answer": "(x-3)^2",
"explaination": ""
},
{
"question": "Show that the following trinomial is a perfect square.",
"sum": "x^2+8x+16",
"answer": "(x+4)^2",
"explaination": ""
}
]
},
]
Dart code:
import 'package:classio_students/bottom_nav.dart';
import 'package:classio_students/colors.dart';
import 'package:classio_students/screens/learn/maths_formula_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_math_fork/flutter_math.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:page_transition/page_transition.dart';
// ignore: must_be_immutable
class Gr11MathQuiz extends StatefulWidget {
var newData;
Gr11MathQuiz({Key? key, required this.newData}) : super(key: key);
#override
_Gr11MathQuizState createState() => _Gr11MathQuizState();
}
class _Gr11MathQuizState extends State<Gr11MathQuiz> {
final TextEditingController _answerController = TextEditingController();
#override
void initState() {
super.initState();
//SystemChannels.textInput.invokeMethod('TextInput.show');
}
#override
Widget build(BuildContext context) {
//Creates a list from the JSON data & shuffles the data quiz in a random order everytime the state changes
List quiz = widget.newData["quiz"];
var randomQuiz = (quiz..shuffle()).first;
//Check answer function
checkAnswer() async {
if (_answerController.text.toString() !=
randomQuiz['answer'].toString()) {
Fluttertoast.showToast(
msg: 'Are you sure? Take a look at your answer.',
gravity: ToastGravity.TOP,
backgroundColor: Colors.orangeAccent,
textColor: Colors.white);
} else {
Fluttertoast.showToast(
msg: 'Nice!',
gravity: ToastGravity.TOP,
backgroundColor: Colors.green,
textColor: Colors.white);
Future.delayed(const Duration(seconds: 1), () {
setState(() {});
_answerController.clear();
});
}
}
final height = MediaQuery.of(context).size.height;
const shape = StadiumBorder();
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: const Text('Gr11 Maths Quiz',
style: TextStyle(
color: titleColor,
letterSpacing: 1,
fontSize: 20,
fontWeight: FontWeight.bold)),
leading: IconButton(
onPressed: () => Navigator.pop(context),
icon: const Icon(
Icons.arrow_back,
color: Colors.black,
size: 30,
)),
actions: [
IconButton(
onPressed: () => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const CustomNavBar())),
icon: const Icon(
Icons.home,
color: Colors.black,
size: 30,
))
],
backgroundColor: Colors.white,
centerTitle: true,
elevation: 0,
),
body: SizedBox(
height: height,
child: Flexible(
child: Padding(
padding: const EdgeInsets.all(13),
child: Column(
children: [
Text(
randomQuiz['question'].toString(),
style: const TextStyle(color: Colors.black, fontSize: 17),
),
const SizedBox(
height: 30,
),
//Sum
Center(
child: Math.tex(
randomQuiz['sum'].toString(),
mathStyle: MathStyle.display,
textStyle: const TextStyle(fontSize: 25),
),
),
const SizedBox(
height: 60,
),
//Answer text
const Align(
alignment: Alignment.centerLeft,
child: Text(
'Answer:',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20),
),
),
const SizedBox(
height: 10,
),
//Answer textfield & check btn
Row(
children: [
//Textfield
Expanded(
child: TextField(
controller: _answerController,
style: const TextStyle(color: Colors.black),
decoration: InputDecoration(
hintText: 'Answer',
hintStyle: const TextStyle(color: Colors.grey),
labelStyle: const TextStyle(color: Colors.grey),
enabledBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.grey),
borderRadius: BorderRadius.circular(13)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(13),
),
focusedBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: submitBtn),
borderRadius: BorderRadius.circular(13))),
),
),
const SizedBox(
width: 15,
),
//Button
Container(
decoration: BoxDecoration(
color: titleColor,
borderRadius: BorderRadius.circular(10)),
child: ElevatedButton(
onPressed: () {
checkAnswer();
},
child: const Text(
"Check",
style: TextStyle(fontSize: 16),
),
style: ElevatedButton.styleFrom(
primary: Colors.transparent,
shadowColor: Colors.transparent,
padding: const EdgeInsets.symmetric(
vertical: 19, horizontal: 20),
//minimumSize: const Size(100.0, 5.0),
textStyle: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 23)),
),
),
],
),
const SizedBox(
height: 20,
),
//View Math symbols dialog
Align(
alignment: Alignment.centerLeft,
child: Container(
decoration: BoxDecoration(
color: Colors.grey.shade400,
borderRadius: BorderRadius.circular(10)),
child: ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return const MathFormulaDialog();
});
},
child: const Text(
"How should I type my answer?",
style: TextStyle(fontSize: 16, color: Colors.black),
),
style: ElevatedButton.styleFrom(
primary: Colors.transparent,
shadowColor: Colors.transparent,
padding: const EdgeInsets.symmetric(
vertical: 19, horizontal: 20),
//minimumSize: const Size(100.0, 5.0),
textStyle: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 23)),
),
),
),
],
),
),
),
));
}
}
try not to use code inside build method unless you want it to be refreshed anytime any little change occurred in widget tree.
basically the problem is here in the very beginning lines of build method:
...
#override
Widget build(BuildContext context) {
List quiz = widget.newData["quiz"];
var randomQuiz = (quiz..shuffle()).first;
...
you must use it outside of build and only use it whenever an action is triggered for example if user finished answering current question then refresh ui and show another random question.
Thanks to #Namini40, I moved the variables to initState() from the build function, the checkAnswer() function remained in the build method and I changed a couple things. If a user gets the answer right rather than using setState() I instead used Navigator.pushReplacement() to navigate to the very same page but will display a different question.
New code: https://github.com/BotsheloRamela/classio/blob/main/quiz_screen.dart
I need some help with this. My task is to pick the location along with the address and submit it. But for some reasons, the _addPointKey.currentState.validate() is always giving false.
I have a TextFormField for taking the address, a location preview container, a button to open the google_map_location_picker and finally a button to submit the data. All these fields are declared inside a form with _addPointKey key.
Form validation does work, i.e. if the fields are empty, it does show in red that the fields can't be empty. But still, I have some problem with submitting the whole formData. The textFormField becomes null.
I have used google_map_location_picker package for picking the location. Can somebody help?
Thanks in advance.
final GlobalKey<FormState> _addPointKey = GlobalKey<FormState>();
Map<String, dynamic> formData = {
"address": null,
};
Widget _addressField() {
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Address of the Collection Center",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Theme.of(context).primaryColor),
),
SizedBox(
height: 10,
),
TextFormField(
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xfff3f3f4),
filled: true),
maxLines: 4,
validator: (String value) {
if (value.isEmpty) {
return "Address is required";
}
return '';
},
onChanged: (String value) {
formData["address"] = value;
},
onSaved: (String value) {
formData["address"] = value;
},
),
],
),
);
}
Widget _locationPreview() {
return (_pickedLocation != null)
? Container(
height: 300,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: Theme.of(context).accentColor,
)),
child: GoogleMap(
initialCameraPosition: CameraPosition(
target: _pickedLocation.latLng,
zoom: 14.4746,
),
markers: Set.from(newMarkers),
),
)
: Container(
child: Text(
"Location is required.",
style: TextStyle(
color: Colors.red,
),
),
);
}
Widget _locationButton() {
return RaisedButton(
color: Theme.of(context).accentColor,
onPressed: () async {
LocationResult result = await showLocationPicker(
context,
< API key>,
initialCenter: LatLng(31.1975844, 29.9598339),
myLocationButtonEnabled: true,
layersButtonEnabled: true,
);
setState(() {
_pickedLocation = result;
_addPointKey.currentState.save();
newMarkers.add(Marker(
markerId: MarkerId("newId"),
draggable: false,
position: _pickedLocation.latLng,
onTap: null,
));
});
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.location_on,
color: Colors.white,
),
Text(
(_pickedLocation == null) ? 'Locate on Map' : 'Change Location',
style: TextStyle(color: Colors.white),
),
],
),
);
}
Widget _addLocationButton() {
return ScopedModelDescendant<MainModel>(
builder: (BuildContext context, Widget widget, MainModel model) {
return model.managingCenter
? CircularProgressIndicator()
: InkWell(
onTap: () async {
print(_addPointKey.currentState.validate());
if (!_addPointKey.currentState.validate() ||
_pickedLocation == null) {
print(formData);
return;
}
_addPointKey.currentState.save();
Map<String, dynamic> successInfo =
await model.addCenter(model.token, formData);
if (successInfo["success"]) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FutureBuilder(
future: model.fetchCenter(model.token),
builder: (context, authResultSnapShot) {
return authResultSnapShot.connectionState ==
ConnectionState.waiting
? SplashScreen()
: CollectionPoints(model);
})));
} else {
print("Something went wrong");
}
},
child: Container(
height: 50,
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.shade200,
offset: Offset(2, 4),
blurRadius: 5,
spreadRadius: 2)
],
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Color(0xfffbb448), Color(0xfff7892b)]),
),
padding: const EdgeInsets.all(10.0),
child: Text('Add the Location',
style: TextStyle(fontSize: 20, color: Colors.white)),
),
);
});
}
void _addPoint() {
showBottomSheet(
context: context,
builder: (context) {
return Container(
padding: EdgeInsets.all(10),
child: Form(
key: _addPointKey,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
_addressField(),
_locationPreview(),
_locationButton(),
_addLocationButton()
],
),
),
),
);
});
}
In the TextFormField validator function you must return null, it indicates the field has correct value and there are no errors. Returning anything other than null will indicate that the field has an invalid value, i've shared the corrected code of the validator function.
TextFormField(
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xfff3f3f4),
filled: true),
maxLines: 4,
validator: (String value) {
if (value.isEmpty) {
return "Address is required";
}
// return ''; this is causing you the error you must return null
return null; // this is correct
},
onChanged: (String value) {
formData["address"] = value;
},
onSaved: (String value) {
formData["address"] = value;
},
),
A simpler way to create a confirm password on your flutter.
'showSnackBar' bottom pop-up to alert users for errors.
[1]: https://i.stack.imgur.com/zjXLd.png
var _password = '';
var _confirmPassword = '';
// this will called 'onTap'
void signUpUser() async {
if (_password != _confirmPassword){ // you can add your statements here
showSnackBar(context,
"Password does not match. Please re-type again.");
} else {
FirebaseAuthMethods(FirebaseAuth.instance).signUpWithEmail(
email: emailController.text,
password: passwordController.text,
context: context,
);
}
}
// Insert inside your build()
// to you password field.
child: TextFormField(
controller: passwordController,
obscureText: true,
onChanged: (value) {
_password = value;
},
// to your confirm password field.
child: TextFormField(
controller: confirmPasswordController,
obscureText: true,
onChanged: (value) {
_confirmPassword = value;
},
// add this to your Sign-up button
onTap: signUpUser,
I am new to flutter this error is giving me a serious nightmare. I have a card list of items called Anchors. These items are coming from the shared preference file which belongs to the logged-in user. In the shared preference Json file, each anchor has one or more distribution centers nested to it. All in a JSON form stored in the shared Preference. Now, I was able to iterate over the anchors respectfully at the first screen but the challenge I am having is when I click on view anchor details button instead of taking me to the details page where I can view the details of that anchor and iterate over the distribution centers of that anchor it doesn't but instead it takes the whole anchors there. I tried to parse only one id to the details page so I can Iterate over the nested objects of that anchor but still its not working. The error message says: type 'int' is not a subtype of type 'List' But if I remove [i]['Oid'] from the link to the details screen it takes the whole data there. They are all on two different screens. Please can anybody help me?
JSON format of:
"Anchors": [
{
"Oid": 11,
"Name": "MAIZE ASSOCIATION OF NIGERIA",
"Acronym": "MAAN",
"DistributionCentres": [
{
"Oid": 11,
"Name": "Logo Centre (Zone A)",
"Address": "Private Warehouse, Ugba, Logo LGA"
},
{
"Oid": 12,
"Name": "Makurdi Centre (Zone B)",
"Address": "Ministry of Agric, Makurdi "
},
{
"Oid": 13,
"Name": "Oturkpo Centre (Zone C)",
"Address": "Private Warehouse, Oturkpo"
},
{
"Oid": 15,
"Name": "Borno MAAN centre",
"Address": "Bolori Store, Flavour Mill, Behind Vita Foam, Maiduguri"
},
{
"Oid": 18,
"Name": "Bauchi Centre",
"Address": "BASPD, Dass Road, Bauchi"
}
],
"NoOfDistributionCentres": 5
},
{
"Oid": 2,
"Name": "MAIZE GROWERS, PROCESSORS AND MARKETERS ASSOCIATION OF NIGERIA",
"Acronym": "MAGPAMAN",
"DistributionCentres": [
{
"Oid": 2,
"Name": "Guma Centre",
"Address": "P 32, 2nd Avenue Federal Housing Estate, N/Bank, Makurdi"
},
{
"Oid": 3,
"Name": "Logo Centre",
"Address": "Terhemen Akema Storage Facility, Ugba, Logo LGA"
},
{
"Oid": 5,
"Name": "Oturkpo Centre",
"Address": "Grain Store, Lower Benue Okele Project, Otukpo"
},
{
"Oid": 6,
"Name": "Gboko Centre",
"Address": "K3 New Road, Opposite former coca cola plant. Solar Schools Street, Gboko"
},
{
"Oid": 7,
"Name": "Gwer East Centre",
"Address": "Ahua Shardye's Warehouse, Behind Sylkan Filling Station, Ikpayongo , G/East LGA"
},
{
"Oid": 8,
"Name": "Kwande Centre",
"Address": "KM 3, Adagi Road, Adikpo"
},
{
"Oid": 9,
"Name": "Ohimini Centre",
"Address": "Ajoga Oglewu, Ohimini"
},
{
"Oid": 10,
"Name": "Oju Centre",
"Address": "Behind Town Hall, Ohuhu owo, Oju LGA"
}
],
"NoOfDistributionCentres": 8
}
],
Anchors Page:
import 'package:erg_app/Details.dart';
import 'package:flutter/material.dart';
import 'package:erg_app/Widgets/nav-drawer.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MaterialApp(
home: AnchorsPage(),
));
class AnchorsPage extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
List<Anchor> _parseAnchors(Map<String, dynamic> map) {
final anchors = <Anchor>[];
for (var anchorMap in map['Anchors']) {
final anchor = Anchor.fromMap(anchorMap);
anchors.add(anchor);
}
return anchors;
}
class Anchor {
final int oId;
final String name;
final String acronym;
final List<DistributionCenter> distributionCenters;
const Anchor({
#required this.oId,
#required this.name,
#required this.acronym,
#required this.distributionCenters,
});
factory Anchor.fromMap(Map<String, dynamic> map) {
final distributionCenters = <DistributionCenter>[];
for (var distribution in map['DistributionCentres']) {
final distributionCenter = DistributionCenter.fromMap(distribution);
distributionCenters.add(distributionCenter);
}
return Anchor(
oId: map['Oid'] as int,
name: map['Name'] as String,
acronym: map['Acronym'] as String,
distributionCenters: distributionCenters,
);
}
}
class DistributionCenter {
final int id;
final String name;
final String address;
const DistributionCenter({
#required this.id,
#required this.name,
#required this.address,
});
factory DistributionCenter.fromMap(Map<String, dynamic> map) {
return DistributionCenter(
id: map['Oid'] as int,
name: map['Name'] as String,
address: map['Address'] as String,
);
}
}
class _MyHomeState extends State<AnchorsPage> {
var user;
var userData;
List anchors = [];
#override
void initState() {
_getUserAnchor();
super.initState();
}
_getUserAnchor() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
setState(() {
anchors = user['Anchors'];
});
print(anchors);
setState(() {
userData = anchors;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: NavDrawer(),
appBar: AppBar(
title: Text('Anchors Details'),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
body: Container(
padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
child: ListView(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(Icons.card_membership,
size: 35, color: Colors.orange[400]),
Text(
'Assigned Anchors',
style: TextStyle(color: Colors.orange[400], fontSize: 25),
),
],
),
ListView.builder(
shrinkWrap: true,
itemCount: anchors.length,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int i) {
return Padding(
padding: const EdgeInsets.all(10.0),
////////////// 1st card///////////
child: Card(
elevation: 4.0,
color: Colors.grey[100],
margin: EdgeInsets.only(
left: 10, right: 10, top: 20, bottom: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Container(
padding: EdgeInsets.only(left: 15, top: 20, bottom: 10),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 50.0,
height: 50.0,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
'assets/images/user.png')))),
),
SizedBox(
width: 20,
),
Text(
anchors[i]['Acronym'],
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 20,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
],
),
Container(width: 10),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Allocated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 70, top: 12),
child: Text(
anchors[i]['Oid'].toString(),
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Validated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 70, top: 12),
child: Text(
anchors[i]['Oid'].toString(),
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Non Validated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 40, top: 12),
child: Text(
anchors[i]['Oid'].toString(),
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Distribution Centers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 60, top: 12),
child: Text(
anchors[i]['Oid'].toString(),
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Daily Inventory Status:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 50, top: 12),
child: Text(
'3',
textAlign: TextAlign.left,
style: TextStyle(
color:Colors.green,
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Container(
height: 20,
),
Row(
children: <Widget>[
/////////// Buttons /////////////
Padding(
padding: const EdgeInsets.all(10.0),
child: FlatButton(
child: Padding(
padding: EdgeInsets.only(
top: 8,
bottom: 8,
left: 10,
right: 8),
child: Text(
'View Details',
textDirection: TextDirection.ltr,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.blueGrey,
shape: new RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(
20.0)),
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
detailsPage(value : anchors[i]['Oid'])));
},
),
),
/////////// End of Buttons /////////////
],
),
],
),
),
),
);
})
],
),
),
);
}
}
Details Page:
import 'package:flutter/material.dart';
class detailsPage extends StatefulWidget {
List value;
detailsPage({Key key, #required this.value}) : super(key: key);
#override
_detailsPageState createState() => _detailsPageState(value);
}
class _detailsPageState extends State<detailsPage> {
List value;
_detailsPageState(this.value);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Anchors Details Page"),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
body: Container(
child: ListView(
children: <Widget>[
Text(value[1]['Name']),
Text(value[1]['Oid'].toString()),
ListView.builder(
shrinkWrap: true,
itemCount: value[1]['DistributionCentres'].length,
//context:context, //it saying the name parameter context is not defined
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int i) {
return Text(value[1]['DistributionCentres'][i]['Name']);
})
],
),
),
);
}
}
Image of what I want to achieve below:
first screen onPressed get the index and assigned it to variable, or you can just pass i varibale too,
onPressed: () {
Navigator.push(context,new MaterialPageRoute(builder: (context) =>
detailsPage(i))); },
In detailed page
class detailsPage extends StatefulWidget {
final int selectedIndex;
detailsPage(this.selectedIndex,{Key key}) : super(key: key);
#override
_detailsPageState createState() => _detailsPageState();
}
place that you want to use the previous page passsed index,
return Text(value[widget.selectedIndex]['DistributionCentres'][i]['Name']);
Hope this will help..
The problem seems to be here
detailsPage(value : anchors[i]['Oid'])
You're passing Oid as parameter that is an Int. But look that the constructor for detailsPage
List value;
detailsPage({Key key, #required this.value}) : super(key: key);
The parameter value is a List. It's hard for me to know what you're trying to do... but you will need to fix this type mismatch.
EDIT
It seems that value parameter should be of type Map<String,dynamic>
class detailsPage extends StatefulWidget {
Map<String, dynamic> value;
detailsPage({Key key, #required this.value}) : super(key: key);
#override
_detailsPageState createState() => _detailsPageState(value);
}
class _detailsPageState extends State<detailsPage> {
Map<String, dynamic> value;
_detailsPageState(this.value);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Anchors Details Page"),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
body: Container(
child: ListView(
children: <Widget>[
Text(value['Name']),
Text(value['Oid'].toString()),
ListView.builder(
shrinkWrap: true,
itemCount: value['DistributionCentres'].length,
//context:context, //it saying the name parameter context is not defined
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int i) {
return Text(value['DistributionCentres'][i]['Name']);
})
],
),
),
);
}
}
And then you should do
detailsPage(value : anchors[i])));
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.