Related
How do i generate JSON from multiple lists using GetX package? I am using GetX package for Flutter to pass data between screens in Flutter. The list is obtained from Episode5.dart file. The list is vieewed in MyApp file which is also the place where JSON Generate Button is kept. On clicking the button, i want the json created using the data in the list above. I have the following code:
1. Episode5.dart
class Episode5 extends StatefulWidget {
#override
_Episode5State createState() => _Episode5State();
}
class _Episode5State extends State<Episode5> {
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
final form = GlobalKey<FormState>();
static var _focusNode = new FocusNode();
bool update = false;
int currentIndex = 0;
List<User> userList = [
User(name: "a", email: "a"),
User(name: "d", email: "b"),
User(name: "c", email: "c"),
];
#override
Widget build(BuildContext context) {
Widget bodyData() => DataTable(
onSelectAll: (b) {},
sortColumnIndex: 0,
sortAscending: true,
columns: <DataColumn>[
DataColumn(label: Text("Name"), tooltip: "To Display name"),
DataColumn(label: Text("Email"), tooltip: "To Display Email"),
DataColumn(label: Text("Update"), tooltip: "Update data"),
],
rows: userList
.map(
(user) => DataRow(
cells: [
DataCell(
Text(user.name),
),
DataCell(
Text(user.email),
),
DataCell(
IconButton(
onPressed: () {
currentIndex = userList.indexOf(user);
_updateTextControllers(user); // new function here
},
icon: Icon(
Icons.edit,
color: Colors.black,
),
),
),
],
),
)
.toList(),
);
return Scaffold(
appBar: AppBar(
title: Text("Data add to List Table using Form"),
),
body: Container(
child: Column(
children: <Widget>[
bodyData(),
Padding(
padding: EdgeInsets.all(10.0),
child: Form(
key: form,
child: Container(
child: Column(
children: <Widget>[
TextFormField(
controller: nameController,
focusNode: _focusNode,
keyboardType: TextInputType.text,
autocorrect: false,
maxLines: 1,
validator: (value) {
if (value.isEmpty) {
return 'This field is required';
}
return null;
},
decoration: new InputDecoration(
labelText: 'Name',
hintText: 'Name',
labelStyle: new TextStyle(
decorationStyle: TextDecorationStyle.solid),
),
),
SizedBox(
height: 10,
),
TextFormField(
controller: emailController,
keyboardType: TextInputType.text,
autocorrect: false,
maxLines: 1,
validator: (value) {
if (value.isEmpty) {
return 'This field is required';
}
return null;
},
decoration: new InputDecoration(
labelText: 'Email',
hintText: 'Email',
labelStyle: new TextStyle(
decorationStyle: TextDecorationStyle.solid)),
),
SizedBox(
height: 10,
),
Column(
children: <Widget>[
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextButton(
child: Text("Add"),
onPressed: () {
form.currentState.save();
addUserToList(
nameController.text,
emailController.text,
);
},
),
TextButton(
child: Text("Update"),
onPressed: () {
form.currentState.save();
updateForm();
},
),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ElevatedButton(
child: Text("Save and Exit"),
onPressed: () {
form.currentState.save();
addUserToList(
nameController.text,
emailController.text,
);
Navigator.pop(context, userList);
},
),
],
),
],
),
),
],
),
],
),
),
),
),
],
),
),
);
}
void updateForm() {
setState(() {
User user = User(name: nameController.text, email: emailController.text);
userList[currentIndex] = user;
});
}
void _updateTextControllers(User user) {
setState(() {
nameController.text = user.name;
emailController.text = user.email;
});
}
void addUserToList(name, email) {
setState(() {
userList.add(User(name: name, email: email));
});
}
}
1. Main.dart
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
return Scaffold(
appBar: AppBar(
title: Text("Testing List View Data From second page to first page"),
),
body: Column(
children: <Widget>[
Expanded(
child: GetBuilder<FormController>(
builder: (controller) => ListView.builder(
itemCount: controller.userList.length,
itemBuilder: (context, index) => Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(controller.userList[index].name),
Text(controller.userList[index].email),
],
),
),
),
),
SizedBox(
height: 10.0,
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Episode5(),
),
);
},
child: Text("Go to Form"),
),
SizedBox(
height: 10.0,
),
ElevatedButton(
onPressed: () {
generateJSON();
},
child: Text("Generate JSON"),
),
],
),
);
}
generateJSON() {
GenerateJSON generate =
GenerateJSON(controller.userList, controller.schooList);
String jsonAddress = jsonEncode(generate);
print(jsonAddress);
}
}
2. Model.dart
class User {
String name;
String email;
User({this.name, this.email});
Map toJson() => {
'name': name,
'age': email,
};
}
class GenerateJSON {
List<User> user;
List<School> school;
GenerateJSON([this.user, this.school]);
Map toJson() {
List<Map> user =
this.user != null ? this.user.map((e) => e.toJson()).toList() : null;
return {'User': user, 'School': school};
}
}
It's exist now a powerful and flexible package on pub.dev named json_bridge.
For those who want to deal with json file, checkout it here: https://pub.dev/packages/json_bridge
Status response code is 200 but the ListView is not displayed and stuck on the CircularProgressIndicator.
When I had 2 items in the Json data it was displaying just fine but as I added another item it doesn't show up!
I've tried removing ListView.separated and using ListView.builder instead and also tried using StreamBuilder but I don't seem to be using it correctly as I'm fairly new to Flutter. If I do have to use StreamBuilder can I be guided through how to use it properly here? Thank You.
Here's my API_manager.dart file:
import 'package:http/http.dart' as http;
import 'package:aritic/models/contactsModel.dart';
// ignore: camel_case_types
class API_Manager {
Future<ContactsModel> getContacts() async {
var client = http.Client();
var contactsModel;
String contacts_url =
'https://exampleapi.com';
String basicAuth = 'Basic auth key example';
try {
var response = await client.get(contacts_url,
headers: <String, String>{'authorization': basicAuth});
print(response.statusCode);
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
contactsModel = ContactsModel.fromJson(jsonMap);
}
} catch (Exception) {
return contactsModel;
}
return contactsModel;
}
}
My UI Code:
import 'package:aritic/models/contactsModel.dart';
import 'package:aritic/services/api_manager.dart';
class ContactsPage extends StatefulWidget {
#override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage>
with SingleTickerProviderStateMixin {
Future<ContactsModel> _contactsModel;
TabController _tabController;
#override
void initState() {
// TODO: implement initState
super.initState();
_tabController = TabController(length: 2, initialIndex: 0, vsync: this);
_tabController.addListener(_handleTabIndex);
_contactsModel = API_Manager().getContacts();
}
#override
void dispose() {
_tabController.removeListener(_handleTabIndex);
_tabController.dispose();
super.dispose();
}
void _handleTabIndex() {
setState(() {});
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Contacts'),
bottom: PreferredSize(
child: Align(
alignment: Alignment.centerLeft,
child: TabBar(
controller: _tabController,
isScrollable: true,
unselectedLabelColor: Colors.white.withOpacity(0.3),
indicatorColor: Colors.white,
tabs: [
Tab(
child: Text('Contacts'),
),
Tab(
child: Text('Companies'),
)
],
),
),
preferredSize: Size.fromHeight(40.0)),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 16.0),
child: IconButton(
icon: Icon(Icons.search),
color: Colors.white,
onPressed: () {},
),
),
],
),
body: TabBarView(controller: _tabController, children: <Widget>[
Container(
height: double.infinity,
child: FutureBuilder<ContactsModel>(
future: _contactsModel,
builder: (BuildContext context,
AsyncSnapshot<ContactsModel> snapshot) {
if (snapshot.hasData) {
return ListView.separated(
shrinkWrap: true,
padding: const EdgeInsets.all(6),
itemCount: snapshot.data.contacts.length,
itemBuilder: (BuildContext context, int index) {
List keys = snapshot.data.contacts.keys.toList();
List values =
snapshot.data.contacts.values.toList();
var contact = values[index];
return InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => ViewContact()));
},
child: Container(
height: 50,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
contact.owner.firstName +
" " +
contact.owner.lastName,
style: TextStyle(fontSize: 16),
),
Text(
contact.owner.username,
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 5,
),
],
),
),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 5,
);
},
);
} else
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.blueGrey[700],
valueColor: AlwaysStoppedAnimation<Color>(
Colors.cyan)));
})),
Container(
height: double.infinity,
child: ListView(
padding: const EdgeInsets.all(6),
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => ViewCompany()));
},
child: Container(
height: 50,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'example company name',
style: TextStyle(fontSize: 16),
),
Text(
'example company domain',
style: TextStyle(fontSize: 14),
)
],
),
),
),
SizedBox(
height: 5,
),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => ViewCompany()));
},
child: Container(
height: 50,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'example company name',
style: TextStyle(fontSize: 16),
),
Text(
'example company domain',
style: TextStyle(fontSize: 14),
)
],
),
),
),
],
)),
]),
floatingActionButton: _bottomButtons(),
));
}
Widget _bottomButtons() {
return _tabController.index == 0
? FloatingActionButton(
shape: StadiumBorder(),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return AddContacts();
}));
},
backgroundColor: Colors.cyan,
child: Icon(
Icons.person_add,
color: Colors.white,
))
: FloatingActionButton(
shape: StadiumBorder(),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return AddCompany();
}));
},
backgroundColor: Colors.cyan,
child: Icon(
Icons.add,
color: Colors.white,
),
);
}
}
Json sample(complete json too big to upload here):
{
"total": "187144",
"contacts": {
"897": {
"isPublished": true,
"id": 897,
"fields": {
"core": {
"points": {
"id": "47",
"label": "Points"
},
"firstname": {
"id": "2",
"label": "First Name",
"value": "Jason"
},
"lastname": {
"id": "3",
"label": "Last Name",
"value": "Lamuda"
},
"...": {
"..." : "..."
}
},
"ipAddresses": [
{
"ip": "70.127.91.131",
"ipDetails": {
"city": "Bradenton",
"region": "Florida",
"timezone": "America/New_York",
}
},
"...": {
"..." : "..."
}
Output Screen(stuck on CircularProgressIndicator): here
create a function like
Future getContacts()async{
_contactsModel = API_Manager().getContacts();
}
then inside your initState
getContacts().then((value){
setState((){});
})
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 have been trying to display data on my flutter app by importing json file in my firebase account but i think there is some error in my code.
class MatchList{
List<MatchListItem> matchList;
MatchList({this.matchList});
factory MatchList.fromJSON(Map<dynamic,dynamic> json){
return MatchList(
matchList: parsematches(json)
);
}
static List<MatchListItem> parsematches(matchJSON){
var mList=matchJSON['browseMatches'] as List;
List<MatchListItem> matchList=mList.map((data) => MatchListItem.fromJson(data)).toList();
return matchList;
}
}
class MatchListItem {
int id;
String title;
String match;
String date;
String desc;
MatchListItem({this.id,this.title,this.match,this.date,this.desc});
factory MatchListItem.fromJson(Map<dynamic,dynamic> parsedJson) {
// print(parsedJson);
return MatchListItem(id: parsedJson['index'],title:parsedJson['title'],match: parsedJson['match'],date:parsedJson['date'],desc:parsedJson['desc']);
}
}
This is my matchListModel.dart file
import 'package:firebase_database/firebase_database.dart';
import 'package:nostra_prediction/matchListModel.dart';
import 'dart:async' show Future;
class MakeCall{
List<MatchListItem> listItems=[];
// ListItem recipeModelList=new ListItem();
Future<List<MatchListItem>> firebaseCalls (DatabaseReference databaseReference) async{
MatchList matchList;
DataSnapshot dataSnapshot = await databaseReference.once();
Map<dynamic,dynamic> jsonResponse=dataSnapshot.value[0]['content'];
matchList = new MatchList.fromJSON(jsonResponse);
print(matchList);
listItems.addAll(matchList.matchList);
// for(var i in matchList.matchList){
// listItems.addAll(matchList.matchList);
// }
// print(matchList.matchList[1].foodtitle);
print('Thatt ${listItems[0].title}');
// return matchList.matchList;
return listItems;
}
}
This is my getMainListInformation.dart file
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:nostra_prediction/constants.dart';
import 'package:nostra_prediction/getMainListInformation.dart';
class Matches extends StatefulWidget{
#override
MatchesList createState()=> MatchesList();
}
class MatchesList extends State<Matches>{
final color = const Color(0xffbfd6ba);
final colorText = const Color(0xffd1bad6);
final databaseReference = FirebaseDatabase.instance.reference();
final makecall= new MakeCall();
#override
Widget build(BuildContext context) {
var futureBuilder=new FutureBuilder(
future: makecall.firebaseCalls(databaseReference), // async work
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Loading....');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index){
// return new Text(snapshot.data[index].foodtitle);
return Card(
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.all(0.0),
child: SizedBox(
height: MediaQuery.of(context).size.height*0.15,
width: MediaQuery.of(context).size.width,
child: Card(
elevation: 0,
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10,right: 5,top: 5),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data[index].title, style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20,fontFamily: 'Roboto-Black'),),
SizedBox(height:10.0),
Row(
children: <Widget>[
new IconTheme(
data: new IconThemeData(
color: Colors.black26),
child: new Icon(Icons.timer,size: 20.0,),
),
Text('${snapshot.data[index].match} minutes',style: TextStyle(fontWeight: FontWeight.w700,color: Colors.black26),)
],
)
],
)
],
),
),
// rightFavFood
],
),
)
],
)
)
),
),
);
},
);
}
},
);
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: color,
centerTitle: true,
// title: Text('Browsing', style: TextStyle(fontFamily: 'Roboto-Black',fontSize: 25,fontWeight: FontWeight.w500,color: Colors.black),),
title : new Image.asset('images/cooking.png'),
actions: <Widget>[
IconButton(icon: Icon(Icons.menu), color: Colors.black26,onPressed: (){print('Menu pressed');},)
],
elevation: 0.0,
),
body: new Column(
children: <Widget>[
new Container(
padding: EdgeInsets.only(top: 5.0,bottom: 10),
color: color,
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ButtonTheme(
minWidth: MediaQuery.of(context).size.width*0.4,
height: MediaQuery.of(context).size.height*0.06,
child:MaterialButton(
onPressed: (){
// MakeCall makecall= new MakeCall();
// var response=makecall.firebaseCalls(databaseReference);
// print(makecall.listItems[0].foodtitle);
// print(makecall.listItems[1].foodtitle);
// new ListView.builder(
// itemCount: makecall.listItems.length,
// itemBuilder: (BuildContext context, int index){
// return
// },
// );
},
color: Colors.white,
// disabledTextColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.horizontal(left: Radius.circular(10.0), right: Radius.circular(1.0))
),
// elevation: 15.0,
splashColor: color,
highlightColor:color,
// highlightElevation: 1.0,
child: Text("Cook Book",style: TextStyle(fontFamily: 'Roboto-Thin ',color: Colors.black26,fontSize: 15),),
) ,
),
ButtonTheme(
minWidth: MediaQuery.of(context).size.width*0.4,
height: MediaQuery.of(context).size.height*0.06,
buttonColor: Colors.amberAccent,
child:MaterialButton(
onPressed: (){Scaffold.of(context).showSnackBar(SnackBar(content: Text('Hey There')));},
color: Colors.white,
// disabledTextColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.horizontal(right: Radius.circular(10.0), left: Radius.circular(1.0))
),
// elevation: 15.0,
highlightColor:color,
// highlightElevation: 1.0,
child: Text("Favourite",style: TextStyle(fontFamily: 'Roboto-Thin ',color: Colors.black26,fontSize: 15)),
) ,
),
],
),
),
SizedBox(height: 0),
new Expanded(
//
child:Container(
child: futureBuilder,
) ,
//
),
],
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: color,
elevation: 20.0,
currentIndex: 0,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home,color: Colors.white,),
title: new Text('Home',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700)),
),
BottomNavigationBarItem(
icon: new Icon(Icons.add_circle,color: Colors.white,),
title: new Text('Add a Recipe',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700))
),
BottomNavigationBarItem(
icon: new Icon(Icons.collections,color: Colors.white,),
title: new Text('My recipes',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700),),
)
],
),
);
}
}
this is my body.dart file
{
"json": [{
"content": {
"browseMatches": [{
"index": 1,
"date" : "12/04/12",
"desc" : "asdfgh",
"match": "abcdefgh",
"title": "wxyz"
}, {
"index": 12,
"date" : "12/04/12",
"desc" : "qwerty",
"match": "abcd",
"title": "xyz"
}
]
}
}]
}
And lastly this is my json data.
I have been trying to display this json data in a listview on card but unable to do so.Please help!
the exact message which gets displayed is:
Error:NoSuchMethodFound.The method '[]' was called on null.
Receiver:null
Tried calling:
I am trying to send the arguments of a "participant" to another screen, I could do it with a ListView and load the list of events, but it is not working in the same way with the participants, now if the list works, but when I tap and I want to see the info of the "participant" everything comes out in null:
In this part I create the participant and generate the list to be able to visualize it, and by giving the tap I send the info of this (according to me)
Widget _crearListadoParticipantes() {
return FutureBuilder<List<Participantes>>(
future: eventosProvider.cargarParticipantes(evento, participantes),
builder: (context, snapshot) {
if ( snapshot.hasData ) {
final participantes = snapshot.data;
return ListView.builder(
itemCount: participantes.length,
itemBuilder: (context, i) {
return _crearParticipante(context, participantes[i], evento);
}
);
} else if (snapshot.hasError){
return Center(child: Text("${snapshot.error}"));
} else {
return Center( child: CircularProgressIndicator());
}
},
);
}
Widget _crearParticipante(BuildContext context, Participantes participantes, EventoModel evento) {
return Padding(
padding: EdgeInsets.all(12.0),
child: GestureDetector(
child: RichText(
softWrap: false,
text: TextSpan(
style: TextStyle(
color: Colors.black,
fontFamily: "Lato_LightItalic",
fontStyle: FontStyle.italic,
fontSize: 20.0,
fontWeight: FontWeight.w400
),
children: [
TextSpan(text: ' '+'${participantes.numero}',
style: TextStyle(
fontWeight: FontWeight.w600
)
),
TextSpan(text: " "),
TextSpan(text: '${participantes.apellido} ${participantes.nombre}',)
],
),
),
onTap: () => Navigator.pushNamed(context, 'destalleParticipante', arguments: evento),
),
);
}
And this is where I am supposed to receive the arguments of the participant to whom I tapped, but as I say, a null returns
class DetalleParticipante extends StatefulWidget {
#override
_DetalleParticipanteState createState() => _DetalleParticipanteState();
}
class _DetalleParticipanteState extends State<DetalleParticipante> {
final eventosProvider = new EventosProvider();
EventoModel evento = new EventoModel();
Participantes participantes = new Participantes();
#override
Widget build(BuildContext context) {
final EventoModel eventoData = ModalRoute.of(context).settings.arguments;
if ( eventoData != null ) {
evento = eventoData;
}
print(participantes.nombre);
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(0),
child: AppBar(
backgroundColor: Color(0xFF249FE2),
),
),
backgroundColor: Colors.white,
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
_encabezadoParticipante(context, AssetImage("assets/icon/info_corredor.png"), participantes, evento),
],
),
),
);
}
Widget _backBottom() {
return FloatingActionButton(
elevation: 0.0,
backgroundColor: Colors.white,
child: Icon(
Icons.arrow_back,
size: 45.0,
color: Colors.black,
),
onPressed: (){
Navigator.pop(context);
},
);
}
Widget _encabezadoParticipante(BuildContext context, AssetImage image, Participantes participantes, EventoModel evento) {
return Container(
color: Colors.grey[600],
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
_backBottom(),
Flexible(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text('${participantes.apellido}',
textAlign: TextAlign.center,
maxLines: 3,
softWrap: true,
style: TextStyle(
color: Colors.white,
fontFamily: "Lato",
fontStyle: FontStyle.italic,
fontSize: 30.0,
fontWeight: FontWeight.bold
),
),
),
),
Image(image: image,
fit: BoxFit.cover,
),
],
),
),
);
}
}