flutter addAll isn't defined for Iterable - json

I need your help for the following problem on line 22.
Flutter says, that "addAll isn't defined for Iterable". What do I need to change in my code or do you need additional Information?
import 'package:flutter/material.dart';
import 'package:MyApp/jsonApi/dataModels/dataModelPlaces.dart';
import 'package:MyApp/jsonApi/parsers/repositoryPlaces.dart';
class ShareAppScreen extends StatefulWidget {
#override
_ShareAppScreenState createState() => _ShareAppScreenState();
}
class _ShareAppScreenState extends State<ShareAppScreen> {
//List<DataModelPlaces> _places = <DataModelPlaces>[];
Iterable<DataModelPlaces> _places = <DataModelPlaces>[];
Iterable<DataModelPlaces> _placesDisplay = <DataModelPlaces>[];
bool _isPlacesLoading = false;
#override
void initState() {
super.initState();
fetchPlaces().then((pvalue) {
setState(() {
_isPlacesLoading = false;
_places.addAll(pvalue); //<- here I have a problem that addAll isn't defined for Iterable
_placesDisplay = _places;
print('User display pin Records: ${pvalue.data!.length}');
var i=0;
while (i < pvalue.data!.length){
print('User display Lat of $i: ${pvalue.data![i].attributes!.latitude}');
print('User display Long of $i: ${pvalue.data![i].attributes!.latitude}');
i++;
}
});
});
}
List stocksList = [
CompanyStocks(name: "Intel Corp", price: 56.96),
CompanyStocks(name: "HP Inc", price: 32.43),
CompanyStocks(name: "Apple Inc", price: 133.98),
CompanyStocks(name: "Microsoft Corporation", price: 265.51)
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Users List ${_places.length}'),
),
body: SafeArea(
child: Container(
child: ListView.builder(
itemCount: stocksList.length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: EdgeInsets.all(10),
child: ListTile(
title: Text(
stocksList[index].name,
style: TextStyle(
fontSize: 20,
),
),
leading: CircleAvatar(
child: Text(
stocksList[index].name[0],
style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
),
),
trailing: Text("\$ ${stocksList[index].price}"),
),
),
);
},
),
),
),
);
}
}
class CompanyStocks {
String name;
double price;
CompanyStocks({required this.name,required this.price});
}
At the End I would need an Variable "_places" and "_placesDisplay" of DataModelPlaces which I can use in in Place of the List "stocksList" which is working but not _places / _placesDisplay"
Many Thanks
Roman

Iterable does not have .addAll. You need to convert it to a List first so you can addAll the elements to it such as:
Update: My bad. toList() will return a new list! You should try the alternative approach below
// This wrong since it will return a new list (wrong)
// _places.toList().addAll(pvalue)
Alternatively, you can change the definition to be List instead of Iterable:
from:
Iterable<DataModelPlaces> _places = <DataModelPlaces>[];
Iterable<DataModelPlaces> _placesDisplay = <DataModelPlaces>[];
To:
List<DataModelPlaces> _places = <DataModelPlaces>[];
List<DataModelPlaces> _placesDisplay = <DataModelPlaces>[];
Update:
As discussed in the comments, you want to make sure that fetchPlaces is returning an Iterable in order to use _places.addAll(pvalue) otherwise, if it's a single object, use _places.add(pvaule).

Related

How to send json data from on route to another route

In my Flutter application, I am trying to pass JSON data from one route to another. The challenge I am facing is how to pass a list as a parameter. The first screen contains a list of JSON data that has been fetched, and I aim to show the complete details of each item when the user clicks on the respective ListTile.
you will find the onTap() in JsonParsingPodo.dart
here's my code :
posts.dart (plain old dart object file)
class PostList {
final List<Post> posts;
PostList({required this.posts});
factory PostList.fromJson(Map<String, dynamic> parsedJson) {
List<dynamic> postsJson = parsedJson['posts'] as List;
List<Post> posts = <Post>[];
posts = postsJson.map((e) => Post.fromJson(e)).toList();
return PostList(posts: posts);
}
}
class Post {
int userId;
int id;
String title;
String body;
Post(
{required this.id,
required this.body,
required this.title,
required this.userId});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
body: json['body'],
title: json['title'],
userId: json['userId']);
}
}
JsonParsingPodo.dart (First Screen)
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:podo_practice/posts.dart';
import 'display.dart';
class JsonParsingPodo extends StatefulWidget {
const JsonParsingPodo({super.key});
#override
State<JsonParsingPodo> createState() => _JsonParsingPodoState();
}
class _JsonParsingPodoState extends State<JsonParsingPodo> {
late Future<PostList> data;
#override
void initState() {
super.initState();
Network network = Network("https://dummyjson.com/posts");
data = network.loadPost();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("PODO: json"),
),
body: Center(
// ignore: avoid_unnecessary_containers
child: Container(
child: FutureBuilder(
future: data,
builder: (context, AsyncSnapshot<PostList> snapshot) {
List<Post> allposts;
if (snapshot.hasData) {
allposts = snapshot.data!.posts;
return createListView(allposts, context);
}
return const CircularProgressIndicator();
}),
),
));
}
Widget createListView(List<Post> data, BuildContext context) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, int index) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Divider(
height: 5.0,
),
ListTile(
title: Text("${data[index].title}"),
subtitle: Text("${data[index].body}"),
leading: Column(
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.green,
radius: 23,
child: Text("${data[index].id}"),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DisplayData()),
// *what to pass here??*
);
},
),
],
);
});
}
}
class Network {
final String url;
Network(this.url);
Future<PostList> loadPost() async {
final response = await get(Uri.parse(Uri.encodeFull(url)));
if (response.statusCode == 200) {
//ok
return PostList.fromJson(json.decode(response.body));
} else {
throw Exception("Failed to load data. ");
}
}
}
DisplayData.dart (Second Screen)
import 'package:flutter/material.dart';
import 'package:podo_practice/posts.dart';
class DisplayData extends StatefulWidget {
const DisplayData({super.key});
#override
State<DisplayData> createState() => _DisplayDataState();
}
class _DisplayDataState extends State<DisplayData> {
late Future<PostList> data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("Display Post"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Column(
children: [
// Text(data);
],
),
),
),
);
}
}
I have recently started learning Flutter and don't have much knowledge. I tried reading articles on Stack Overflow about this thing, but I didn't understand much. So, I have decided to post a question for help. Please assist me in completing the following code.
On the "Display Data" page, I need to display the **title **and its **description **when the user clicks on the ListItem.
onListile tap send particular object using index
Widget createListView(List<Post> data, BuildContext context) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, int index) {
Post post = data[index]
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Divider(
height: 5.0,
),
ListTile(
title: Text("${data[index].title}"),
subtitle: Text("${data[index].body}"),
leading: Column(
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.green,
radius: 23,
child: Text("${data[index].id}"),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DisplayData(post:post)),
// *what to pass here??*
);
},
),
],
);
});
}
}
get post on constructor to display
import 'package:flutter/material.dart';
import 'package:podo_practice/posts.dart';
class DisplayData extends StatefulWidget {
final Post post;
const DisplayData({super.key,required this.post});
#override
State<DisplayData> createState() => _DisplayDataState();
}
class _DisplayDataState extends State<DisplayData> {
late Future<PostList> data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("Display Post"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Column(
children: [
// Text(data);
],
),
),
),
);
}
}

How to generate a List to the second screen in flutter from a JSON?

I am trying to create a list from the value inside a JSON. I can get the length but not for the data. My main goal is to create a list of items based on their popularity.
child: Row(
children: [
...List.generate(
"items"[0].length,
(index) {
if (["items"][index].isPopular) { // here I want to generate a list for the value isPopular
return BreakfastCard(breakfast: ('items'[0] as Map<String, dynamic>[index]); // Here I want to call the function from other screen
}
And when I tried to change the code to this
"items"[0].length,
(index) {
if (["items"][index][isPopular]) { // the error here is *Conditions must have a static type of 'bool'.*
return BreakfastCard(breakfast: ['items'][0][index]); // the error here is *The argument type 'String' can't be assigned to the parameter type 'Breakfast'.*
The JSON data is like this
{
"items":[{
"id": 1,
"rating": "0.0",
"images": [
"assets/images/cilantro.png"
],
"title": "Cilantro and Kale Pesto Toast with a Fried Egg",
"time": 15,
"description": "Sliced bread is the perfect blank canvas, ready to be loaded up with virtuous ingredients.",
" rating": "4.8",
"isFavorite": false,
"isPopular": true,
}]
}
Here is my code for the card. In this part, there were no error and it show what I want.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fema/models/Breakfast.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../constants.dart';
import '../size_config.dart';
class BreakfastCard extends StatefulWidget {
BreakfastCard({
Key? key,
this.width = 140,
this.aspectRetio = 1.02,
required this.breakfast,
}) : super(key: key);
final double width, aspectRetio;
Breakfast breakfast;
#override
_BreakfastCardState createState() => _BreakfastCardState();
}
class _BreakfastCardState extends State<BreakfastCard> {
#override
Widget build(BuildContext context) {
Future<String> _loadloadBreakfastAsset() async {
return await rootBundle.loadString('assets/breakfast.json');
}
Future<BreakfastCard> loadBreakfast() async {
String jsonAddress = await _loadloadBreakfastAsset();
final jsonResponse = json.decode(jsonAddress);
// This now updates the breakfast property in the main class.
widget.breakfast = Breakfast.fromJson(jsonResponse);
// This return value is thrown away, but this line is necessary to
// resolve the Future call that FutureBuilder is waiting on.
return Future<BreakfastCard>.value();
}
SizeConfig().init(context);
return FutureBuilder(
future: loadBreakfast(),
builder: (BuildContext, AsyncSnapshot<dynamic>snapshot){
return Padding(
padding: EdgeInsets.only(left: getProportionateScreenWidth(20)),
child: SizedBox(
width: getProportionateScreenWidth(140),
child: GestureDetector(
onTap: (){},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AspectRatio(
aspectRatio: 1.02,
child: Container(
padding: EdgeInsets.all(getProportionateScreenWidth(20)),
decoration: BoxDecoration(
color: kSecondaryColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(15),
),
child: Hero(
tag: widget.breakfast.id.toString(),
child: Image.asset(widget.breakfast.images[0]),
),
),
),
const SizedBox(height: 10),
Text(
widget.breakfast.title,
style: const TextStyle(color: Colors.black),
maxLines: 2,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"${widget.breakfast.calories} cal |",
style: TextStyle(
fontSize: getProportionateScreenWidth(18),
fontWeight: FontWeight.bold,
color: kPrimaryColor,
),
),
Text(
"${widget.breakfast.time} min",
style: TextStyle(
fontSize: getProportionateScreenWidth(18),
fontWeight: FontWeight.w600,
color: kPrimaryColor,
),
),
InkWell(
borderRadius: BorderRadius.circular(50),
onTap: () { widget.breakfast.isFavorite = !widget.breakfast.isFavorite;},
child: Container(
padding: EdgeInsets.all(getProportionateScreenWidth(8)),
height: getProportionateScreenWidth(28),
width: getProportionateScreenWidth(28),
child: SvgPicture.asset(
"assets/icons/Heart Icon_2.svg",
color: widget.breakfast.isFavorite
? const Color(0xFFFF4848)
: const Color(0xFFDBDEE4),
),
),
),
],
)
],
),
),
),
);
}
);
}
}
And my problem is in here. Where the list will be generated. I am new to flutter and I have difficulties to solve the problem. In here I can correctly create a function to fetch the data from the BreakfastCard.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fema/components/breakfast_card.dart';
import 'package:fema/models/Breakfast.dart';
import 'package:flutter/services.dart';
import '../../../size_config.dart';
import 'section_title.dart';
class Breakfast extends StatelessWidget {
const Breakfast({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
Future<String> _loadloadBreakfastAsset() async {
return await rootBundle.loadString('assets/breakfast.json');
}
Future<Breakfast> loadBreakfast() async {
String jsonAddress = await _loadloadBreakfastAsset();
Map<String,dynamic> map = json.decode(jsonAddress);
List<dynamic> items = map["items"];
// This return value is thrown away, but this line is necessary to
// resolve the Future call that FutureBuilder is waiting on.
return Future<Breakfast>.value();
}
return FutureBuilder(
future: loadBreakfast(),
builder: (BuildContext, AsyncSnapshot<dynamic>snapshot){
return Column(
children: [
Padding(
padding:
EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)),
child: SectionTitle(title: "BREAKFAST", press: () {}),
),
SizedBox(height: getProportionateScreenWidth(20)),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
...List.generate(
items[0].length,
(index) {
if (items[index].isPopular) {
return BreakfastCard(breakfast: );
}
return const SizedBox
.shrink(); // here by default width and height is 0
},
),
SizedBox(width: getProportionateScreenWidth(20)),
],
),
)
],
);
});
}
}
You need to put "items" into a Map first. You are trying to use the String object "items" to populate your list. You want the data from the json to populate it.
Get the data into a usable object first.
Map<String, dynamic> map = jsonDecode(data);
List<dynamic> items = map["items"];
Then you can populate your list from that data.
child: Row(
children: [
...List.generate(
items.length,
(index) {
if (items[index].isPopular) {
return BreakfastCard(breakfast: (items[0]));
}
Your errors are from trying to use json data improperly as the conditional for an if statement.
The other error is because you are trying to send a String as an argument for a Breakfast object when it needs something else (I don't know what that is. You didn't post what a BreakfastCard class looks like at the time I wrote this.)
Dart and Flutter documentation is very good. Try this out https://flutter.dev/docs/development/data-and-backend/json

Error: type 'List<dynamic>' is not a subtype of type 'String'

I am new to flutter. I am trying to fetch the data from Firestore by Stream. But it is giving me error. I am trying to fetch a String and a List but I don't know what to change in code to fetch the List. In code, 'name' field is String and 'overview' field is a List.
import 'package:firebaseAuth/firebaseAuthDemo.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class FindDiseases extends StatefulWidget {
final User user;
const FindDiseases({Key key, this.user}) : super(key: key);
#override
_FindDiseasesState createState() => _FindDiseasesState();
}
class _FindDiseasesState extends State<FindDiseases> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
FirebaseAuth _auth = FirebaseAuth.instance;
List diseasesList = [];
dynamic data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
//automaticallyImplyLeading: false,
title: Text(
"Diseases List",
),
),
key: _scaffoldKey,
body: Container(
color: Colors.white,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection("diseases")
.orderBy('id')
.snapshots(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot user = snapshot.data.docs[index];
return Card(
color: Colors.white,
child: FlatButton(
onPressed: () {},
child: ListTile(
title: Text(user['name']),
subtitle: Text(user['overview']),
),
),
);
},
);
},
),
),
);
}
Data is something like as shown below:
"name": "Agoraphobia",
"overview": "[
'Losing weight.', 'Stopping medications or supplements.', 'Having surgery.'
]"
It is because you are using
subtitle: Text(user['overview']),
as a string while in data this data is in list format try to get index wise data from it then try to show as string
In your data "overview" is a type of list and you are trying to get it as string.
List<String> list = user['overview'];
String data = String.join(", ", list);
return Card(
color: Colors.white,
child: FlatButton(
onPressed: () {},
child: ListTile(
title: Text(user['name']),
subtitle: Text(data),
),
),
);

How to put the result of a function into a Text widget in Flutter?

I am new in this language and I am working on a BMI(body mass index) app. As you see in the picture below:
I take the user input and calculate the result, and print out the result in console. For example:
I/flutter ( 4500): 2.25
I/flutter ( 4500): 20.0 // this is the result of BMI
I/flutter ( 4500): you are at your ideal weight. // this is the explanation
I want to show these results in a Text widget to let user see them. But I do not know how to do it. How can I take the value of the result from a function and add it to interface?
Here is my code, and in code I pointed out where did I stuck. Main function:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'calculation.dart';
void main() => runApp(MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'BMI';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title),
centerTitle: true,
backgroundColor: Colors.amber[900],
),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
enum SingingCharacter { lafayette, jefferson }
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
SingingCharacter _character = SingingCharacter.lafayette;
double height=1;
double weight=1;
String info1="";
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10.0),
child:Scrollbar(
child:SingleChildScrollView(
child:Card(
color: Colors.amber[50],
child:Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 10, 10),
child: Text("Sex:",
style:TextStyle(fontSize: 24, letterSpacing: 1.0)),
),
ListTile(
title: const Text('Female',
style:TextStyle(fontSize: 18, letterSpacing: 1.0)
),
leading: Radio(
activeColor: Colors.orange,
value: SingingCharacter.lafayette,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
),
ListTile(
title: const Text('Male',
style:TextStyle(fontSize: 18, letterSpacing: 1.0,)
),
leading: Radio(
activeColor: Colors.orange,
value: SingingCharacter.jefferson,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
),
SizedBox(height: 10.0),
Text("Your height:",
style:TextStyle(fontSize: 24, letterSpacing: 1.0)
),
SizedBox(height: 10),
Padding(
padding: const EdgeInsets.fromLTRB(30, 0, 50, 10),
child: TextField(
decoration: new InputDecoration(labelText: "Your height(cm)"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
onSubmitted: (input1){
if(double.parse(input1)>0){
setState(() => height=double.parse(input1));
print(input1);
}
},
),
),
SizedBox(height: 20),
Text("Your weight:",
style:TextStyle(fontSize: 24, letterSpacing: 1.0)
),
SizedBox(height: 10),
Padding(
padding: const EdgeInsets.fromLTRB(30, 0, 50, 10),
child: new TextField(
decoration: new InputDecoration(labelText: "Your weight(kg)"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
onSubmitted: (input2){
if (double.parse(input2)>0){
// print(weight);
setState(() {
return weight=double.parse(input2);
});
}
},
),),
SizedBox(height: 10,),
RaisedButton(
padding:EdgeInsets.fromLTRB(20, 5, 20, 5),
onPressed: () async{
await Calculation(height, weight);
// return Calculation.info1 ??? //i don't know how to take info1 from calculation function
},
color: Colors.amber[900],
child:Text(
'Calculate',
style:TextStyle(
color: Colors.white,
fontSize: 30,
letterSpacing: 2.0,
),
),
),
SizedBox(height: 20,),
Text('Results: $height,$weight'),
// Text('Calculation.info1'), // i do not know how to show info in a text box.
],
),
),
),
),
);
}
}
Calculation function;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';
void Calculation(height,weight) {
double squarevalue = pow(height, 2);
double newsquare = squarevalue / 10000;
String info1="";
print(newsquare);
double value = weight / newsquare;
print(value);
// return value.toString();
if (value < 18.5) {
print("your weight is less than your ideal weight.");
// setState(() => info1="your weight is less than your ideal weight."); //i do not know how to set
// info1 to a new text
// return info1;
}
if (value > 25) {
if (value > 30) {
print("your weight is more than your ideal weight, your health is under risk.");
// info1="your weight is more than your ideal weight, your health is under risk.";
}
else {
print("your weight is more than your ideal weight.");
// info1="your weight is more than your ideal weight.";
}
}
else {
print("you are at your ideal weight.");
// info1="you are at your ideal weight.";
}
}
Instead of returning void from Calculation(height,weight) function, return String and display the string value in the Text Widget.
String Calculation(height,weight) {
....// your code with all conditions
return "you are at your ideal weight."
}
In onpressed function, update the obtained string to the state variable inside setState.
onPressed: () async{
String info = await Calculation(height, weight);
setState(){
infoDisplayedInText = info;
}
},

How can we use JSON with datatable?

I am new on flutter but I work a lot for learning all I need for my projects.
I have a JSON sent by a server using HTTP:
[{"equipe1":"PSG","equipe2":"DIJON","type_prono":"1N2"},{"equipe1":"MONACO","equipe2":"REIMS","type_prono":"1N2"},{"equipe1":"TOULOUSE","equipe2":"RENNES","type_prono":"1N2"},{"equipe1":"MONTPELLIER","equipe2":"STRASBOURG","type_prono":"1N2"},{"equipe1":"AMIENS","equipe2":"METZ","type_prono":"1N2"},{"equipe1":"BREST","equipe2":"ANGERS","type_prono":"1N2"},{"equipe1":"LORIENT","equipe2":"CHAMBLY","type_prono":"1N2"}]
And I try to set it to a datatable widget but it seems complicated to do.
Now here is my entire code :
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
// Create a Form widget.
class Affiche_grille extends StatefulWidget {
#override
Affiche_grille_State createState() {
return Affiche_grille_State();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class Affiche_grille_State extends State<Affiche_grille> {
#override
final _formKey = GlobalKey<FormState>();
Grille_display() async {
// SERVER LOGIN API URL
var url = 'http://www.axis-medias.fr/game_app/display_grid.php';
// Store all data with Param Name.
var data = {'id_grille': 1};
// Starting Web API Call.
var response = await http.post(url, body: json.encode(data));
// Getting Server response into variable.
var match = json.decode(response.body);
}
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
var listmatch = Grille_display();
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
DataTable(
columnSpacing: 20,
columns: [
DataColumn(
label: Text("Eq 1"),
numeric: false,
tooltip: "",
),
DataColumn(
label: Text("Eq 2"),
numeric: false,
tooltip: "",
),
DataColumn(
label: Text("Type pro"),
numeric: false,
tooltip: "",
),
],
rows: EquipeList.map((equipe_detail) => DataRow(
cells: [
DataCell(
Text(equipe_detail['equipe1'].toString()),
),
DataCell(
Text(equipe_detail['equipe2'].toString()),
),
DataCell(
Text(equipe_detail['type_prono'].toString()),
),
]),
).toList(),
)
],
)
);
}
}
class Match_detail {
String equipe1;
String equipe2;
String typeProno;
Match_detail({this.equipe1, this.equipe2, this.typeProno});
Match_detail.fromJson(Map<String, dynamic> json) {
equipe1 = json['equipe1'];
equipe2 = json['equipe2'];
typeProno = json['type_prono'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['equipe1'] = this.equipe1;
data['equipe2'] = this.equipe2;
data['type_prono'] = this.typeProno;
return data;
}
}
class EquipeList {
List<Match_detail> breeds;
EquipeList({this.breeds});
factory EquipeList.fromJson(List<dynamic> json) {
return EquipeList(
breeds: json
.map((e) => Match_detail.fromJson(e as Map<String, dynamic>))
.toList());
}
}
It doesn't work :( it says me : error: The method 'map' isn't defined for the class 'EquipeList'. (undefined_method at [flutter_app] lib
You can copy paste run full code below
You can use package https://pub.dev/packages/json_table
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:json_table/json_table.dart';
class SimpleTable extends StatefulWidget {
#override
_SimpleTableState createState() => _SimpleTableState();
}
class _SimpleTableState extends State<SimpleTable> {
final String jsonSample =
'[{"equipe1":"PSG","equipe2":"DIJON","type_prono":"1N2"},{"equipe1":"MONACO","equipe2":"REIMS","type_prono":"1N2"},{"equipe1":"TOULOUSE","equipe2":"RENNES","type_prono":"1N2"},{"equipe1":"MONTPELLIER","equipe2":"STRASBOURG","type_prono":"1N2"},{"equipe1":"AMIENS","equipe2":"METZ","type_prono":"1N2"},{"equipe1":"BREST","equipe2":"ANGERS","type_prono":"1N2"},{"equipe1":"LORIENT","equipe2":"CHAMBLY","type_prono":"1N2"}]';
bool toggle = true;
#override
Widget build(BuildContext context) {
var json = jsonDecode(jsonSample);
return Scaffold(
body: Container(
padding: EdgeInsets.all(16.0),
child: toggle
? Column(
children: [
JsonTable(
json,
showColumnToggle: true,
tableHeaderBuilder: (String header) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: 8.0, vertical: 4.0),
decoration: BoxDecoration(
border: Border.all(width: 0.5),
color: Colors.grey[300]),
child: Text(
header,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.display1.copyWith(
fontWeight: FontWeight.w700,
fontSize: 14.0,
color: Colors.black87),
),
);
},
tableCellBuilder: (value) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: 4.0, vertical: 2.0),
decoration: BoxDecoration(
border: Border.all(
width: 0.5,
color: Colors.grey.withOpacity(0.5))),
child: Text(
value,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.display1.copyWith(
fontSize: 14.0, color: Colors.grey[900]),
),
);
},
allowRowHighlight: true,
rowHighlightColor: Colors.yellow[500].withOpacity(0.7),
paginationRowCount: 20,
),
SizedBox(
height: 20.0,
),
Text("Simple table which creates table direclty from json")
],
)
: Center(
child: Text(getPrettyJSONString(jsonSample)),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.grid_on),
onPressed: () {
setState(
() {
toggle = !toggle;
},
);
}),
);
}
String getPrettyJSONString(jsonObject) {
JsonEncoder encoder = new JsonEncoder.withIndent(' ');
String jsonString = encoder.convert(json.decode(jsonObject));
return jsonString;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SimpleTable(),
);
}
}
I think you should first, convert this json into a real dart class so it can be easier to work with. You could create a class in dart/flutter called "Equipe" and run a map on the json. The [] means that you're dealing with a list of data.
But if you don't want to create a class, you could definitely work with with the json response, mapping over the list. I'm going to try to cook it up for you quickly. NB: Just remember to convert the json too, if it hasn't been done yet.
DataTable(
columnSpacing: 20,
columns: [
DataColumn(
label: Text("Eq 1"),
numeric: false,
tooltip: "",
),
DataColumn(
label: Text("Eq 2"),
numeric: false,
tooltip: "",
),
DataColumn(
label: Text("Type pro"),
numeric: false,
tooltip: "",
),
],
rows: equipeDetails.map((equipeDetail) => DataRow(
cells: [
DataCell(
Text(equipeDetail['equipe1'].toString()),
),
DataCell(
Text(equipeDetail['equipe2'].toString()),
),
DataCell(
Text(equipeDetail['type_prono'].toString()),
),
]),
).toList(),
)
I have done it:
Grille_display() async {
// SERVER LOGIN API URL
var url = 'http://www.axis-medias.fr/game_app/display_grid.php';
// Store all data with Param Name.
var data = {'id_grille': 1};
// Starting Web API Call.
var response = await http.post(url, body: json.encode(data));
// Getting Server response into variable.
var match = json.decode(response.body);
}
I think I need to create 2 class, instead of using equipeDetails and equipeDetail.
I need to display only equipe1 and equipe2 in table and use type prono for display radio button 1N2 or 12.
To populate data Table with json, create 2 methods .
One for populating the column headings.
Second one for populating the rows.
then pass the methods as value to datatable.
DataTable(
columnSpacing: 20,
columns:
dataTableColumnHeaderSetter(
dashBoardItems!
.oSsummary),
rows: dashBoardItems!.oSsummary
.mapIndexed(
(index, details) => DataRow(
cells:
dataTableColumnValueSetter(
dashBoardItems!
.oSsummary),
),
)
.toList()),
Method one.
List<DataColumn> dataTableColumnHeaderSetter(List<OSsummary> summary) {
return List.generate(summary.length, (i) {
return DataColumn(
label: Text(
summary[i].head,
textAlign: TextAlign.center,
),
numeric: true,
tooltip: "",
);
});
}
Method Two.
List<DataCell> dataTableColumnValueSetter(List<OSsummary> summary) {
return List.generate(summary.length, (i) {
return DataCell(
Text(
summary[i].value,
textAlign: TextAlign.center,
),
showEditIcon: false,
placeholder: false,
);
});
}
Do wrap the datatable in future builder and use snapshot.data for accessing the json data.