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.
Related
I am trying to select an index from a list of images in flutter. While passing the image list to the Image.network() i get an error:
The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 500, http://10.0.2.2:8000/static/product_images/b0bf3474f9c5a6b6cfcf.jpg,http://10.0.2.2:8000/static/product_images/e307dccf6bbc2700e683.jpg,http://10.0.2.2:8000/static/product_images/6e91cff1ce07d72fc127.jpg
Please how do i seperate the images so that only the index i pick is selected?
Below is the Product Model:
import 'dart:convert';
List<ProductModel> productsFromJson(String str) => List<ProductModel>.from(
json.decode(str).map((x) => ProductModel.fromJson(x)));
String productsToJson(List<ProductModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ProductModel {
ProductModel({
required this.name,
required this.price,
required this.isActive,
required this.imgsUrl,
required this.id,
required this.description,
required this.ownerId,
});
String name;
double price;
bool isActive;
List<String> imgsUrl;
int id;
String description;
int ownerId;
factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
name: json["name"],
price: json["price"].toDouble(),
isActive: json["is_active"],
imgsUrl: List<String>.from(json["imgs_url"].map((x) => x)),
id: json["id"],
description: json["description"],
ownerId: json["owner_id"],
);
Map<String, dynamic> toJson() => {
"name": name,
"price": price,
"is_active": isActive,
"imgs_url": List<dynamic>.from(imgsUrl.map((x) => x)),
"id": id,
"description": description,
"owner_id": ownerId,
};
}
I am using a futurebuilder with dio to fetch the data from the API:
FutureBuilder<List<ProductModel>>(
future: productModel,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('${snapshot.error}');
} else if (snapshot.hasData) {
debugPrint('${snapshot.data}');
return SizedBox(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Container(
decoration: const BoxDecoration(
color: styles.AppColors.facebookBlue),
child: Text('$finalName products online'),
),
),
Expanded(
child: StaggeredGridView.countBuilder(
crossAxisCount: 2,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(children: [
Container(
height: 180,
width: double.infinity,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(4)),
child:
Image.network(snapshot
.data![index].imgsUrl[0])
]),
const SizedBox(
height: 8,
),
Text(snapshot.data![index].name),
Text(
"\$${snapshot.data![index].price.toString()}",
)
],
),
),
);
},
staggeredTileBuilder: (int index) =>
const StaggeredTile.fit(1),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
),
],
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
}),
For the API call with DioClient:
Future<List<ProductModel>> fetchVProduct() async {
await SecureStorage.readSecureData("vt")
.then((value) => finalToken = value);
try {
final response = await Dio().get(
'$productsEndpoint/me/items/',
options: Options(
headers: {
'Content-Type':
'application/x-www-form-urlencoded;charset=UTF-8;application/json;multipart/form-data',
'Accept': 'application/json',
"Authorization": "Bearer $finalToken",
},
followRedirects: false,
validateStatus: (status) {
return status! < 500;
}),
);
debugPrint(response.toString());
return (response.data as List)
.map((x) => ProductModel.fromJson(x))
.toList();
} on DioError catch (e) {
debugPrint("Status code: ${e.response?.statusCode.toString()}");
throw Exception("Failed to load currently Logged in Vendor Products");
}
}
For the sample json from my apicall:
{
"name": "sa",
"price": 44,
"is_active": true,
"imgs_url": [
"http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],
"id": 43,
"description": "hfg",
"owner_id": 1
}
Please what do i do next? Thank you.
In data imgs_url is a single string containing three urls.
"imgs_url": [
"http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],
Change it to
"imgs_url": [
"http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg",
"http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg",
"http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],
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'm having trouble displaying 'option' and getting (print in terminal) the 'id' of the chosen option.
How can I retrieve the json as map and use it effectively in flutter_form_builder?
Here is the json object:
{
id: 7,
poll: What is the capital of Egypt?,
created_at: 2020-10-22 10:53:41,
votes_count: 4,
likes_count: 0,
options: [
{
id: 20,
option: Tunis,
pollId: 7,
votes_count: 1
}, {
id: 21,
option: Cairo,
pollId: 7,
votes_count: 3
}, {
id: 22,
option: New York,
pollId: 7,
votes_count: 0
}],
user_name: salem,
user_image: null,
topics: []
}
Here is my poll_details page:
import 'package:flutter/material.dart';
import 'package:circular_profile_avatar/circular_profile_avatar.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:like_button/like_button.dart';
import '../services/poll_services.dart';
import '../widgets/loading_widget.dart';
class PollDetails extends StatefulWidget {
final id;
PollDetails({this.id});
#override
_PollDetailsState createState() => _PollDetailsState(id);
}
class _PollDetailsState extends State<PollDetails> {
var id;
_PollDetailsState(this.id);
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
#override
void initState() {
super.initState();
optionsList.clear();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(title: Text("Details")),
body: FutureBuilder(
future: singlePoll(id),
builder: (context, snapshot) {
if(snapshot.hasData){
return ListView(
padding: EdgeInsets.fromLTRB(18, 40, 18, 0),
children: [
Padding(
padding: EdgeInsets.only(bottom: 20),
child: Container(
padding: EdgeInsets.fromLTRB(10, 40, 0, 40),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: Theme.of(context).primaryColor,
width: 5.0,
style: BorderStyle.solid
)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
if(imgPath(snapshot.data) == null) CircleAvatar(radius: 35,child: Image.asset('images/avatar.png'))
else CircularProfileAvatar(
imgPath(snapshot.data),
radius: 35,
borderWidth: 3.0,
borderColor: Colors.white,
backgroundColor: Colors.transparent,
foregroundColor: Colors.transparent,
errorWidget: (context, url, error) => Container(child: Icon(Icons.error)),
placeHolder: (context, url) => Container(
width: 50,
height: 50,
child: Text("Loading image..."),
)
),
SizedBox(width: 10.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
userName(snapshot.data),
style: TextStyle(fontSize: 20)
),
Flexible(
fit: FlexFit.loose,
child: Text(
votesCount(snapshot.data).toString()+" participants to this poll",
style: TextStyle(fontSize: 13)
)
)
]
)
)
]
)
)
),
///////////////////////////////// POLLS //////////////////////////////////////////////
FormBuilder(
key: _fbKey,
autovalidateMode: AutovalidateMode.always,
child: FormBuilderRadioGroup(
attribute: 'options',
decoration: InputDecoration(labelText: 'Choose only one:'),
validators: [FormBuilderValidators.required()],
orientation: GroupedRadioOrientation.vertical,
options: [
for (var i in optionsList) i['option'].toString()
]
.map((option) => FormBuilderFieldOption(value: option))
.toList(growable: false),
)
),
RaisedButton(
child: Text("Submit"),
onPressed: () async{
_fbKey.currentState.save();
if (_fbKey.currentState.validate()) {
// Loading().show(context);
var option = _fbKey.currentState.value['options'];
print(option);
// var resp = await createPoll(question, tagS, choiceS);
// if(resp['status'] == "success"){
// Navigator.pop(context); //pop dialog
// } else {
// Navigator.pop(context); //pop dialog
// }
}
}
),
//////////////////////////// Like Button ///////////////////////////////
Row(
children: [
LikeButton(
size: 40,
circleColor:
CircleColor(start: Colors.red, end: Colors.red),
bubblesColor: BubblesColor(
dotPrimaryColor: Colors.red,
dotSecondaryColor: Colors.red,
),
likeBuilder: (bool isLiked) {
return Icon(
Icons.favorite,
color: isLiked ? Colors.red : Colors.grey,
size: 40,
);
},
likeCount: likes(snapshot.data),
countBuilder: (int count, bool isLiked, String text) {
var color = isLiked ? Colors.red : Colors.grey;
Widget result;
if (count == 0) {
result = Text(
"0",
style: TextStyle(color: color),
);
} else
result = Text(
text,
style: TextStyle(color: color),
);
return result;
}
),
Expanded(child: Text(" have liked this. Show some love, too!"))
]
),
Column(
children: [
// optionsList.forEach((element) => Text('option'))
for (var i in optionsList) Text(i['option'].toString())
]
),
RaisedButton(
child: Text("data"),
onPressed: (){singlePoll(id);}
)
]
);
}else {
return Center(child: CircularProgressIndicator());
}
}
)
)
);
}
}
And here is the request I use to get the response:
Future singlePoll(int id) async {
String url = baseUrl+"poll/get";
var stringID = id.toString();
var token = await storage.read(key: "jwt");
try{
final response = await http.post(
url,
headers: {'Accept':'application/json', 'Authorization':token},
body: {'pollId':stringID}
);
var dataToJson = jsonDecode(response.body);
for (var option in dataToJson['options']){
var optionID = option['id'];
var optionTitle = option['option'].toString();
var votesCount = option['votes_count'];
optionsList.add(option);
}
print(dataToJson);
return dataToJson;
} catch (e){
print('error caught: $e');
}
}
As you can see, I used a work around to get the list and display it.
Any suggestion is valuable.
Thanks in advance...
You need to use setState() in here:
setState() {
var optionID = option['id'];
var optionTitle = option['option'].toString();
var votesCount = option['votes_count'];
optionsList.add(option);
}
You can read more from the official document and look at here.
I have the Following json file and I have used it to generate a dropdown list. The goal is to store the price when a user searches for a given service. The list shows the fields which are then used for the search but the prices are the accumulated.
{
"services": [
{
"price": 3,
"service": "Caregiver"
},
{
"price": 5,
"service": "Driver"
},
{
"price": 0,
"service": "Tipper Driver"
}
],
"locations": [
{
"sub_county": "All of NY"
},
{
"sub_county": "Brkln"
}
]
}
Here is the drop down field code
DropdownButtonFormField<String>(
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(10, 0, 10, 0),
filled: true,
fillColor: Theme.Colors.color_7,
hintText: 'Select a Profession',
hintStyle: TextStyle(fontWeight: FontWeight.bold)),
value: _listdownValue,
icon: Icon(Icons.arrow_drop_down),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.black),
onChanged: (String newValue) {
setState(() {
_listdownValue = newValue;
});
},
validator: (value) {
if (value == null) {
return "Select a Profession";
}
return null;
},
items: snapshot.data.services.map((item) {
return new DropdownMenuItem(
child: new Text(item.service),
value: item.service.toString(),
);
}).toList(),
),