Related
when click the showModalBottomSheet it's show on the screen
Null Check operator used on a null value
can anyone help to figure out which is the code error? kindly refer full code as below, TQ!
class ProductContentFirst extends StatefulWidget {
final List _productContentList;
const ProductContentFirst(this._productContentList, {Key? key})
: super(key: key);
#override
State<ProductContentFirst> createState() => _ProductContentFirstState();
}
class _ProductContentFirstState extends State<ProductContentFirst> {
ProductContentItem? _productContent;
List _attr = [];
#override
void initState() {
super.initState();
_productContent = widget._productContentList[0];
this._attr = this._productContent!.attr!;
//print(this._attr);
}
List<Widget>? _getAttrItemWidget(attrItem) {
List<Widget> attrItemList = [];
attrItem.list.forEach((item) {
attrItemList.add(Container(
margin: EdgeInsets.all(5),
child: Chip(
label: Text("${item}"),
padding: EdgeInsets.all(10),
),
));
print (item);
});
}
List<Widget>? _getAttrWidget() {
List<Widget> attrList = [];
this._attr.forEach((attrItem) {
attrList.add(Wrap(
children: [
Container(
width: ScreenAdapter.width(80.0),
child: Padding(
padding: EdgeInsets.only(top: ScreenAdapter.height(30.0)),
child: Text(
"${attrItem.cate}",
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
),
Container(
width: ScreenAdapter.width(600.0),
child: Wrap(
//children: [],
children: _getAttrItemWidget(attrItem)!,
),
)
],
));
print(attrItem.cate);
});
//return null;
}
_attrBottomSheet() {
showModalBottomSheet(
context: context,
builder: (context) {
return GestureDetector(
onTap: () {
false;
},
child: Stack(
children: [
Container(
padding: EdgeInsets.all(10),
child: ListView(
children: [
Column(
children: _getAttrWidget()!,
)
],
),
),
Positioned(
bottom: 0,
width: ScreenAdapter.width(750.0),
height: ScreenAdapter.height(100),
child: Row(
children: [
Expanded(
flex: 1,
child: Container(
child: JdButton(
color: Color.fromRGBO(253, 1, 0, 0.9),
text: "Add Cart",
cb: () {
print("Add Cart");
},
),
)),
Expanded(
flex: 1,
child: Container(
child: JdButton(
color: Color.fromRGBO(255, 165, 0, 0.9),
text: "Buy",
cb: () {
print("Buy");
},
),
)),
],
))
],
),
);
});
}
#override
Widget build(BuildContext context) {
String pic = Config.domain + this._productContent!.pic!;
pic = pic.replaceAll("\\", "/");
return Container(
padding: EdgeInsets.all(10.0),
child: ListView(
children: [
AspectRatio(
aspectRatio: 16 / 12,
child: Image.network(
"${pic}",
fit: BoxFit.cover,
),
),
Container(
padding: EdgeInsets.only(top: 7),
child: Text(
"${this._productContent!.title}",
style: TextStyle(
color: Colors.black87, fontSize: ScreenAdapter.size(36)),
),
),
Container(
padding: EdgeInsets.only(top: 7),
child: Text(
"${this._productContent!.subTitle}",
style: TextStyle(
color: Colors.black54, fontSize: ScreenAdapter.size(28)),
),
),
Container(
padding: EdgeInsets.only(top: 7),
child: Row(
children: [
Expanded(
flex: 1,
child: Row(
children: [
Text("Price: "),
Text(
"${this._productContent!.price}",
style: TextStyle(
color: Colors.red,
fontSize: ScreenAdapter.size(46)),
)
],
),
),
Expanded(
flex: 1,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text("Old Price: "),
Text(
"${this._productContent!.oldPrice}",
style: TextStyle(
color: Colors.black38,
fontSize: ScreenAdapter.size(32),
decoration: TextDecoration.lineThrough),
),
],
),
),
],
),
),
Container(
margin: EdgeInsets.only(top: 7),
height: ScreenAdapter.height(80.0),
child: InkWell(
onTap: () {
_attrBottomSheet();
},
child: Row(
children: [
Text(
"Select:",
style: TextStyle(fontWeight: FontWeight.bold),
),
Text("115, Black, XL, 1 pcs")
],
),
),
),
Divider(),
Container(
height: ScreenAdapter.height(80.0),
child: Row(
children: [
Text(
"Delivery Fees:",
style: TextStyle(fontWeight: FontWeight.bold),
),
Text("Free Delivery")
],
),
),
Divider(),
],
),
);
}
}
class ProductContentModel {
ProductContentItem? result;
ProductContentModel({this.result});
ProductContentModel.fromJson(Map<String, dynamic> json) {
result = json['result'] != null
? new ProductContentItem.fromJson(json['result'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.result != null) {
data['result'] = this.result!.toJson();
}
return data;
}
}
class ProductContentItem {
String? sId;
String? title;
String? cid;
Object? price;
String? oldPrice;
Object? isBest;
Object? isHot;
Object? isNew;
String? status;
String? pic;
String? content;
String? cname;
List<Attr>? attr;
String? subTitle;
Object? salecount;
ProductContentItem(
{this.sId,
this.title,
this.cid,
this.price,
this.oldPrice,
this.isBest,
this.isHot,
this.isNew,
this.status,
this.pic,
this.content,
this.cname,
this.attr,
this.subTitle,
this.salecount});
ProductContentItem.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
title = json['title'];
cid = json['cid'];
price = json['price'];
oldPrice = json['old_price'];
isBest = json['is_best'];
isHot = json['is_hot'];
isNew = json['is_new'];
status = json['status'];
pic = json['pic'];
content = json['content'];
cname = json['cname'];
if (json['attr'] != null) {
attr = <Attr>[];
json['attr'].forEach((v) {
attr!.add(new Attr.fromJson(v));
});
}
subTitle = json['sub_title'];
salecount = json['salecount'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['title'] = this.title;
data['cid'] = this.cid;
data['price'] = this.price;
data['old_price'] = this.oldPrice;
data['is_best'] = this.isBest;
data['is_hot'] = this.isHot;
data['is_new'] = this.isNew;
data['status'] = this.status;
data['pic'] = this.pic;
data['content'] = this.content;
data['cname'] = this.cname;
if (this.attr != null) {
data['attr'] = this.attr!.map((v) => v.toJson()).toList();
}
data['sub_title'] = this.subTitle;
data['salecount'] = this.salecount;
return data;
}
}
class Attr {
String? cate;
List<String>? list;
Attr({this.cate, this.list});
Attr.fromJson(Map<String, dynamic> json) {
cate = json['cate'];
list = json['list'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['cate'] = this.cate;
data['list'] = this.list;
return data;
}
}
When the exception was thrown, this was the stack:
\#0 \_ProductContentFirstState.\_getAttrWidget.\<anonymous closure (package:flutter_jdshop/pages/ProductContent/ProductContentFirst.dart:64:54)
Don't use ! without checking null. While the snippet is large, follow these steps.
Check null, and then perform operation the place you've used !. It will be like if(result!=null)result.add(new FocusItemModel.fromJson(v));
the children can be children: _getAttrItemWidget(attrItem)??[]
You aren't returning widgets from _getAttrItemWidget and others. It will be
List<Widget> _getAttrItemWidget(attrItem) { // no need to return null
List<Widget> attrItemList = [];
attrItem.list.forEach((item) {
....
print (item);
});
return attrItemList;
}
In short Don't use ! without checking null. or provide default value on null case.
Find more about null-safety.
I am fairly new to using REST API to GET data and display in a Listview in Flutter. I have since been working on something like this, But i get Lost along the line. Hence I need Help with this.
My code Goes thus
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class TransactionDetails {
final String avatar;
final String name;
final String date;
final String amount;
TransactionDetails({required this.avatar, required this.name, required this.date, required this.amount});
factory TransactionDetails.fromJson(Map<String, dynamic> json) {
return TransactionDetails(
avatar: json['avatar'],
name: json['name'],
date: json['date'],
amount: json['amount']);
}
}
class BaseScreen extends StatelessWidget {
const BaseScreen({Key? key}) : super(key: key);
Future<TransactionDetails> fetchTransaction() async {
final response = await http
.get('https://brotherlike-navies.000webhostapp.com/people/people.php');
if (response.statusCode == 200) {
return TransactionDetails.fromJson(json.decode(response.body));
} else {
throw Exception('Request Failed.');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: double.infinity,
height: 150,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
color: Colors.green,
alignment: Alignment.center,
child: const Text(
'\$5200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
color: Colors.green,
alignment: Alignment.center,
child: const Text(
'\$1200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
SizedBox(height: 24),
],
),
),
Padding(
padding: EdgeInsets.all(15),
child: Text(
"Recent Transactions",
style: TextStyle(
fontSize: 14, fontWeight: FontWeight.bold, color: Colors.green),
),
),
ListView() //Display the data here from the REST API
],
)));
}
}
How do I Display it on the Listview? Please I need help with this. Just for the sake of clarification as I am learning here with this.
Try below code:
Your TransactionDetails Class
class TransactionDetails {
String? avatar;
String? name;
String? date;
String? amount;
TransactionDetails({
this.avatar,
this.name,
this.date,
this.amount,
});
TransactionDetails.fromJson(Map<String, dynamic> json) {
avatar = json['avatar'];
name = json['name'];
date = json['date'];
amount = json['amount'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['avatar'] = avatar;
data['name'] = name;
data['date'] = date;
data['amount'] = amount;
return data;
}
}
API Call:
Future<List<TransactionDetails>> fetchAlbum() async {
final response = await http.get(Uri.parse(
'https://brotherlike-navies.000webhostapp.com/people/people.php'));
if (response.statusCode == 200) {
final List result = json.decode(response.body);
return result.map((e) => TransactionDetails.fromJson(e)).toList();
} else {
throw Exception('Failed to load data');
}
}
Your Widget:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: double.infinity,
height: 150,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
color: Colors.green,
alignment: Alignment.center,
child: const Text(
'\$5200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
Container(
margin: const EdgeInsets.all(15),
width: 319,
height: 100,
color: Colors.green,
alignment: Alignment.center,
child: const Text(
'\$1200.00',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
const SizedBox(height: 24),
],
),
),
const Padding(
padding: EdgeInsets.all(15),
child: Text(
"Recent Transactions",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.green),
),
),
Center(
child: FutureBuilder<List<TransactionDetails>>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
child: Image.network(
snapshot.data![index].avatar.toString()),
),
title: Text(snapshot.data![index].name.toString()),
trailing:
Text(snapshot.data![index].amount.toString()),
subtitle: Text(snapshot.data![index].date.toString()),
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
],
),
Result Screen->
There are multiple ways you can achieve this.
Using FutureBuilder
Using StatefulWidget & setState
Currently, you are using a StatelessWidget (BaseScreen) so let's just go with FutureBuilder.
On hitting the url that you have given:
https://brotherlike-navies.000webhostapp.com/people/people.php
It gives the following response:
[{"avatar":"https:\/\/static.vecteezy.com\/system\/resources\/thumbnails\/002\/002\/403\/small\/man-with-beard-avatar-character-isolated-icon-free-vector.jpg","name":"Kayo Johnson","date":"09\/29\/2022","amount":"5000.00"},{"avatar":"https:\/\/static.vecteezy.com\/system\/resources\/thumbnails\/002\/002\/403\/small\/man-with-beard-avatar-character-isolated-icon-free-vector.jpg","name":"Kuta Joy","date":"09\/29\/2022","amount":"5000.00"},{"avatar":"https:\/\/static.vecteezy.com\/system\/resources\/thumbnails\/001\/993\/889\/small\/beautiful-latin-woman-avatar-character-icon-free-vector.jpg","name":"Timmi Phillips","date":"09\/28\/2022","amount":"3500.00"}]
It returns a list of transaction details objects. Hence, you should add another method in your model TransactionDetail which will return a list of TransactionDetails as follows:
class TransactionDetails {
final String avatar;
final String name;
final String date;
final String amount;
TransactionDetails(
{required this.avatar,
required this.name,
required this.date,
required this.amount});
factory TransactionDetails.fromJson(Map<String, dynamic> json) {
return TransactionDetails(
avatar: json['avatar'],
name: json['name'],
date: json['date'],
amount: json['amount']);
}
static List<TransactionDetails> fromJsonList(dynamic jsonList) {
final transactionDetailsList = <TransactionDetails>[];
if (jsonList == null) return transactionDetailsList;
if (jsonList is List<dynamic>) {
for (final json in jsonList) {
transactionDetailsList.add(
TransactionDetails.fromJson(json),
);
}
}
return transactionDetailsList;
}
}
Update your fetchTransaction method as follows:
Future<List<TransactionDetails>> fetchTransaction() async {
final response = await http
.get('https://brotherlike-navies.000webhostapp.com/people/people.php');
if (response.statusCode == 200) {
return TransactionDetails.fromJsonList(json.decode(response.body));
} else {
throw Exception('Request Failed.');
}
}
Just wrap your ListView widget with a FutureBuilder widget as follows:
FutureBuilder(
future: fetchTransaction(),
builder: (context, AsyncSnapshot<List<TransactionDetails>> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.data == null) {
return const Center(child: Text('Something went wrong'));
}
return ListView.builder(
itemCount: snapshot.data?.length ?? 0,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data![index].name),
subtitle: Text(snapshot.data![index].amount),
);
});
}
return const CircularProgressIndicator();
},
),
i am beginner in FLutter , i have a json that i want to send to internet by flutter
this is the json i want to send:
{
"userid": 41,
"name": "dhya",
"price": 11,
"players": [
{
"id":1,
"firstname":"aa",
"lastname":"ee",
"position":"df",
"price":12.1,
"appearences":2,
"goals":1,
"assists":1,
"cleansheets":1,
"redcards":1,
"yellowcards":1,
"image":"qq"
},
{
"id":2,
"firstname":"aa",
"lastname":"ee",
"position":"df",
"price":12.1,
"appearences":2,
"goals":1,
"assists":1,
"cleansheets":1,
"redcards":1,
"yellowcards":1,
"image":"qq"
}
]
}
As a beginner , i did not have any idea about how to send an object that the server will receive in the json format that i wanted so i used a quicktype and i created this model
// To parse this JSON data, do
//
// final clubJson = clubJsonFromJson(jsonString);
import 'dart:convert';
ClubJson clubJsonFromJson(String str) => ClubJson.fromJson(json.decode(str));
String clubJsonToJson(ClubJson data) => json.encode(data.toJson());
class ClubJson {
ClubJson({
this.userid,
this.name,
this.price,
this.players,
});
int userid;
String name;
int price;
List<Player> players;
factory ClubJson.fromJson(Map<String, dynamic> json) => ClubJson(
userid: json["userid"],
name: json["name"],
price: json["price"],
players: List<Player>.from(json["players"].map((x) => Player.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"userid": userid,
"name": name,
"price": price,
"players": List<dynamic>.from(players.map((x) => x.toJson())),
};
}
class Player {
Player({
this.id,
this.firstname,
this.lastname,
this.position,
this.price,
this.appearences,
this.goals,
this.assists,
this.cleansheets,
this.redcards,
this.yellowcards,
this.image,
this.clubid,
});
int id;
String firstname;
String lastname;
String position;
double price;
int appearences;
int goals;
int assists;
int cleansheets;
int redcards;
int yellowcards;
String image;
int clubid;
factory Player.fromJson(Map<String, dynamic> json) => Player(
id: json["id"],
firstname: json["firstname"],
lastname: json["lastname"],
position: json["position"],
price: json["price"].toDouble(),
appearences: json["appearences"],
goals: json["goals"],
assists: json["assists"],
cleansheets: json["cleansheets"],
redcards: json["redcards"],
yellowcards: json["yellowcards"],
image: json["image"],
clubid: json["clubid"],
);
Map<String, dynamic> toJson() => {
"id": id,
"firstname": firstname,
"lastname": lastname,
"position": position,
"price": price,
"appearences": appearences,
"goals": goals,
"assists": assists,
"cleansheets": cleansheets,
"redcards": redcards,
"yellowcards": yellowcards,
"image": image,
"clubid": clubid,
};
}
And now in the end the only remaining step is the function that i wrote in FLutter:
Future <void> PostRequest() async {
// set up POST request arguments
final url = Uri.parse('http://localhost:3000/api/questions/addQuestion');
Map<String, String> headers = {"Content-type": "application/json"};
ClubJson club = ClubJson(userid: 1, name: "dsds", price: 55.2,players: null );
for(var item in widget.selectedPlayers){
club.players.add(Player(id:item.playerID,firstname:item.firstName,lastname:item.lastName,position:item.position,price:item.price,appearences:item.appearances,goals:item.goals,assists:item.assists,cleansheets:item.cleanSheets,redcards:item.redCards,yellowcards:item.yellowCards,image:item.image));
}
String json = club.toJson().toString();
print(club);
// make POST request
Response response = await post(url, headers: headers, body: json);
// check the status code for the result
int statusCode = response.statusCode;
// this API passes back the id of the new item added to the body
String body = response.body;
}
After i clicked on the button to call the function PostRequest() and send the object to internet i got a strange message and the call is not done:
======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
https://api.flutter.dev/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
The context used was: CreateTeamView
state: _CreateTeamViewState#c4658
When the exception was thrown, this was the stack:
#0 Scaffold.of (package:flutter/src/material/scaffold.dart:1472:5)
#1 _CreateTeamViewState.build.<anonymous closure> (package:footyappp/Fantazyy/create_team_view.dart:325:36)
#2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
#3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
#4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#eeb07
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(187.1, 658.5)
finalLocalPosition: Offset(187.1, 25.1)
button: 1
sent tap down
====================================================================================================
Here the full code of Flutter:
import 'package:flutter/material.dart';
import 'package:footyappp/Fantazyy/club_json.dart';
import 'package:footyappp/Fantazyy/controller.dart';
import 'package:footyappp/Fantazyy/styles.dart';
import 'package:footyappp/Fantazyy/player%20copy.dart';
import 'package:footyappp/Fantazyy/players_creation_details_view.dart';
import 'package:http/http.dart';
class CreateTeamView extends StatefulWidget {
List<Playerr> selectedPlayers;
CreateTeamView({
Key key,
players,
selectedPlayers,
}) : selectedPlayers = (selectedPlayers == null) ? new List<Playerr>.generate(16, (int index) => null) : selectedPlayers;
#override
_CreateTeamViewState createState() => _CreateTeamViewState();
}
class _CreateTeamViewState extends State<CreateTeamView> {
Future <void> PostRequest() async {
// set up POST request arguments
final url = Uri.parse('http://localhost:3000/api/questions/addQuestion');
Map<String, String> headers = {"Content-type": "application/json"};
ClubJson club = ClubJson(userid: 1, name: "dsds", price: 55.2,players: null );
for(var item in widget.selectedPlayers){
club.players.add(Player(id:item.playerID,firstname:item.firstName,lastname:item.lastName,position:item.position,price:item.price,appearences:item.appearances,goals:item.goals,assists:item.assists,cleansheets:item.cleanSheets,redcards:item.redCards,yellowcards:item.yellowCards,image:item.image));
}
String json = club.toJson().toString();
print(club);
// make POST request
Response response = await post(url, headers: headers, body: json);
// check the status code for the result
int statusCode = response.statusCode;
// this API passes back the id of the new item added to the body
String body = response.body;
}
final double _checkboxHeight = 30.0;
double _startingBudget = 107.0;
double _budget = 107.0;
bool _everyTeam = false, _minThreeFreshers = false, _maxThreeSameTeam = true, _isTeamNameLong = false, _buttonEnabled = true;
String _teamName = "";
Widget _saveChanges = Text("Press to save changes");
#override
void initState() {
Map<int,int> teamCount = new Map<int, int>();
int fresherCount = 0;
for (Playerr player in widget.selectedPlayers) {
if (player != null) {
_budget -= player.price;
/* if (teamCount[player.club] == null) {
teamCount[player.teams] = 1;
} else {
teamCount[player.teams]++;
if (teamCount[player.club] > 3) _maxThreeSameTeam = false;
}*/
}
}
_minThreeFreshers = (fresherCount >= 3);
_everyTeam = (teamCount.length >=7);
super.initState();
}
emptyPlayer(int index) {
Playerr player = widget.selectedPlayers[index];
Widget playerView;
if (player == null) {
playerView = Image.asset("Assets/shirt_blank.png", fit: BoxFit.fitHeight,);
} else {
playerView = Column(
children: <Widget>[
Expanded(
child: Image.asset(player.image, fit: BoxFit.fitHeight,),
),
Container(
color: Colors.green,
child: Text(player.firstName.substring(0,1) + ". " + player.lastName, textAlign: TextAlign.center, softWrap: false, overflow: TextOverflow.fade,),
),
Container(
color: Colors.green,
child: Text("£${player.price}m", textAlign: TextAlign.center),
),
],
);
}
return Expanded(
child: InkWell(
onTap: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) {return PlayersCreationDetailsView(selectedPlayers: widget.selectedPlayers, playerIndex: index,);})),
child: Padding(padding: EdgeInsets.only(left: 3.0, right: 3.0), child:playerView,)
),
);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
appBar: AppBar(title: Text("Create your team"),),
body: Stack(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: Stack(
children: <Widget>[
Positioned.fill(
child: Image.asset("Assets/pitch.jpg", fit: BoxFit.fitWidth, alignment: Alignment.topLeft,)
)
]
)
),
],
),
Column( //players
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 1,
child: Container()
),
Expanded(
flex: 6,
child: Padding(
padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: List.generate(2, (index) => emptyPlayer(index)),
),
)
),
Expanded(
flex: 1,
child: Container()
),
Expanded(
flex: 6,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: List.generate(5, (index) => emptyPlayer(index+2)),
)
),
Expanded(
flex: 1,
child: Container()
),
Expanded(
flex: 6,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: List.generate(5, (index) => emptyPlayer(index+7)),
)
),
Expanded(
flex: 1,
child: Container()
),
Expanded(
flex: 6,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: List.generate(4, (index) => emptyPlayer(index+12)),
)
),
Expanded(
flex: 1,
child: Container()
),
Container(
color: Styles.colorAccentDark,
padding: EdgeInsets.only(left: 8.0, right: 8.0),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 4.0, bottom: 4.0),
child: Row(
children: <Widget>[
Expanded(
child: Text("Remaining Budget", style: Styles.budgetLabel,),
),
Text("£${_budget}m", style: Styles.budgetLabel,)
],
),
),
Row(
children: <Widget>[
Expanded(
child: Text("At least one player from every team:", style: Styles.checkboxLabel),
),
Container(
height: _checkboxHeight,
child: Checkbox(
value: _everyTeam,
onChanged: (bool) => null,
),
)
],
),
Row(
children: <Widget>[
Expanded(
child: Text("At least two freshers:", style: Styles.checkboxLabel),
),
Container(
height: _checkboxHeight,
child: Checkbox(
value: _minThreeFreshers,
onChanged: (bool) => null,
),
)
],
),
Row(
children: <Widget>[
Expanded(
child: Text("Max three players from same team:", style: Styles.checkboxLabel),
),
Container(
height: _checkboxHeight,
child: Checkbox(
value: _maxThreeSameTeam,
onChanged: (bool) => null,
),
)
],
),
Padding(
padding: EdgeInsets.only(bottom: 4.0),
child: Row(
children: <Widget>[
Expanded(
child: TextField(
onChanged: (string) {
if (string.length >= 4) {
_teamName = string;
setState(() {
_isTeamNameLong = true;
});
} else {
setState(() {
_isTeamNameLong = false;
});
}
},
decoration: InputDecoration(
fillColor: Styles.colorBackgroundLight,
filled: true,
hintText: "Team Name",
),
)
),
Container(
height: _checkboxHeight,
child: Checkbox(
value: _isTeamNameLong,
onChanged: (bool) => null,
),
)
],
),
)
],
),
)
,
new MaterialButton(
height: 50.0,
minWidth: double.infinity,
color: Styles.colorButton,
splashColor: Colors.teal,
textColor: Colors.white,
child: _saveChanges,
onPressed: () {
if (_buttonEnabled) {
String message = "";
if (!_everyTeam) {
message +=
"You need at least one player from every team \n";
}
if (!_minThreeFreshers) {
message +=
"You need at least 3 freshers in your team \n";
}
if (!_maxThreeSameTeam) {
message +=
"You can have at most 3 players from the same team \n";
}
if (!_isTeamNameLong) {
message +=
"Your team name must be at least 4 characters long \n";
}
if (_budget < 0) {
message += "You can't exceed the budget \n";
}
if (message != "") {
final snackBar = SnackBar(
content: Text(message),
duration: Duration(seconds: 2)
);
Scaffold.of(context).showSnackBar(snackBar);
setState(() {
_saveChanges = FutureBuilder(
future: PostRequest(),
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
_buttonEnabled = true;
return Text("Press to save changes");
}
// By default, show a loading spinner and disable button
_buttonEnabled = false;
return CircularProgressIndicator();
},
);
}); }
}
}
),
],
),
],
)
)
);
}
}
try adding a key for scaffold widget like this
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
Scaffold(
key: scaffoldKey,
body:....
scaffoldKey.currentState.showSnackBar(snackBar);
or if you are using flutter 2 use this to show SnackBar
ScaffoldMessenger.of(context).showSnackBar(snackBar)
I am beginner in flutter ,I used an API of soccer to get some information of player transferts ,so I have created a model class that contains only the information that I need to ,but when I executed, I had this error:
E/flutter ( 5073): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter ( 5073): #0 new Transferts.fromJson (package:tl_fantasy/models/transfert_json.dart:12:26)
E/flutter ( 5073): #1 _PlayerDetailsState.getTeams.<anonymous closure>.<anonymous closure> (package:tl_fantasy/players/player_details.dart:45:45)
So I changed my model class
if i put this in the model class it works when i put it for example json['transfers'][0]['date'], but the problem is it gives me only the first result , what i need is all results, how to replace[0] by a kind of index or something? how to take all elements?
Here the json that i am trying to access:
{
"response": [
{
"player": {
"id": 35845,
"name": "Hernán Darío Burbano"
},
"update": "2020-02-06T00:08:15+00:00",
"transfers": [
{
"date": "2019-07-15",
"type": "Free",
"teams": {
"in": {
"id": 2283,
"name": "Atlas",
"logo": "https://media.api-sports.io/football/teams/2283.png"
}
}
},
{
"date": "2019-01-01",
"type": "N/A",
"teams": {
"in": {
"id": 1937,
"name": "Atletico Atlas",
"logo": "https://media.api-sports.io/football/teams/1937.png"
}
}
}
]
}
]
}
Here my model class tranfert_json:
class Response {
Player player;
String update;
List<Transfers> transfers;
Response({this.player, this.update, this.transfers});
Response.fromJson(Map<String, dynamic> json) {
player = json['player'] != null ? new Player.fromJson(json['player']) : null;
update = json['update'];
if (json['transfers'] != null) {
transfers = new List<Transfers>();
json['transfers'].forEach((v) { transfers.add(new Transfers.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.player != null) {
data['player'] = this.player.toJson();
}
data['update'] = this.update;
if (this.transfers != null) {
data['transfers'] = this.transfers.map((v) => v.toJson()).toList();
}
return data;
}
}
class Player {
int id;
String name;
Player({this.id, this.name});
Player.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
class Transfers {
String date;
String type;
Teams teams;
Transfers({this.date, this.type, this.teams});
Transfers.fromJson(Map<String, dynamic> json) {
date = json['date'];
type = json['type'];
teams = json['teams'] != null ? new Teams.fromJson(json['teams']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
data['type'] = this.type;
if (this.teams != null) {
data['teams'] = this.teams.toJson();
}
return data;
}
}
class Teams {
In teamIn;
Teams({this.teamIn});
Teams.fromJson(Map<String, dynamic> json) {
teamIn = json['in'] != null ? new In.fromJson(json['in']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.teamIn != null) {
data['in'] = this.teamIn.toJson();
}
return data;
}
}
class In {
int id;
String name;
String logo;
In({this.id, this.name, this.logo});
In.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
logo = json['logo'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['logo'] = this.logo;
return data;
}
}
Here my player_details class:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:tl_fantasy/models/transfert_json.dart';
class PlayerDetails extends StatefulWidget {
int id;
String name;
String lastname;
String image;
String club;
String position;
String nationality;
String age;
int matches;
String goals;
String assists;
String saves;
PlayerDetails({this.id,this.name, this.lastname,this.image, this.club, this.position,
this.nationality, this.age, this.matches, this.goals, this.assists, this.saves});
#override
_PlayerDetailsState createState() => _PlayerDetailsState();
}
class _PlayerDetailsState extends State<PlayerDetails> {
List<Response> teams = [];
Future<void> getTeams(int id) async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/transfers?player=$id',
headers: {'x-rapidapi-key': 'c52370f8295e1525b7f7ba38655e243f',
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
teams = clubList
.map((dynamic item) => Response.fromJson(item))
.toList();
});
}
#override
void initState() {
super.initState();
getTeams(widget.id);
}
#override
Widget build(BuildContext context) {
if(widget.matches == null ){
widget.matches == 0;
}
if(widget.goals == null ){
widget.goals == "0";
}
if(widget.assists == null ){
widget.assists == "0";
}
if(widget.saves == null ){
widget.saves == "0";
}
List<Stats> stats = [
Stats("Matches", widget.matches.toString() ),
Stats("Goals", widget.goals ),
Stats("Assists", widget.assists ),
Stats("Saves", widget.saves ),
];
return Scaffold(
appBar: AppBar(
title: Text("Player Details"),
backgroundColor: Colors.blue[300],
elevation: 0.0,
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Colors.purple, Colors.blue])
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.purple, Colors.black38])),
child: ListView(
children: [
SizedBox(
height: 20,
),
Container(
margin: EdgeInsets.fromLTRB(8.0,0,8.0,0),
width: double.infinity,
child: Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child:
Row(
children: <Widget>[
Container(
height: 60,
width: 60,
child:
Image.network(this.widget.image,
),
),
const SizedBox(width:10.0),
Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget> [
Text(widget.name, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
Text(widget.lastname, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
const SizedBox(height: 5.0, ),
Text(widget.club, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
const SizedBox(height: 5.0, ),
Text("Role : "+widget.position, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
const SizedBox(height: 5.0, ),
Text("Age : "+widget.age, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
const SizedBox(height: 5.0, ),
Text("Nationality : "+widget.nationality, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
],
),
],
),
),
),
),
Container(
margin: EdgeInsets.fromLTRB(10, 15, 0, 0),
child: Text(
"Season Stats",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Colors.white),
),
),
SizedBox(
height: 10,
),
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: stats.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0
),
itemBuilder: (BuildContext context, int index){
return Card(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
alignment: Alignment.topCenter,
padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
child: Text(stats[index].result,style: TextStyle(fontSize: 20.0)),
),
Container(
alignment: Alignment.bottomCenter,
child: Text(stats[index].title,style: TextStyle(fontSize: 25.0)),),
]
),
),
);
},
)
),
SizedBox(
height: 10,
),
Container(
margin: EdgeInsets.fromLTRB(10, 0, 0, 10),
child: Text(
"Teams",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Colors.white),
),
),
SizedBox(
height: 10,
),
Container(
margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
child: ListView.builder(
shrinkWrap: true,
physics : NeverScrollableScrollPhysics(),
itemBuilder: (context, index){
return Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child:
Row(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(teams[index].transfers[index].teams.teamIn.logo),
),
const SizedBox(width:10.0),
Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget> [
Text(teams[index].transfers[index].teams.teamIn.name, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0,
)),
const SizedBox(height: 5.0, ),
Text("joined : "+teams[index].transfers[index].date, style: TextStyle( fontWeight:FontWeight.bold,
fontSize: 18.0, color: Colors.grey[600],
)),
],
),
],
),
),
);
},
itemCount: teams.length,
),
),
SizedBox(
height: 70,
),
],
),
)
),
);
}
}
class Stats{
String title;
String result;
Stats(this.title,this.result);
}
class Team {
String name;
String image;
String date;
Team(this.name,this.image,this.date);
}
i am trying to find a way to get all results , not just the first index of my api json
Example of nested ListviewBuilder , don't forget to add shrinkWrap inside the listview
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
shrinkWrap: true,
itemCount: teams.length,
itemBuilder: (BuildContext context, int index) {
List<Transfers> transfers = teams[index].transfers;
return ListView.builder(
shrinkWrap: true,
itemCount: transfers.length,
itemBuilder: (BuildContext context, int index) {
return Text(transfers[index].teams.teamIn.name);
},
) ;
},
),
);
}
I am trying to create dynamically rows widget inside column widget. I am new to flutter, I tried my best but still failed to fixed the issue. I would like to request you please help me in this issue. I added all stuff which I tried. Thank you so much
My Json
{
"status": true,
"data": {
"id": 1,
"image": "https://img.taste.com.au/fruCLEZM/taste/2019/08/chicken-karahi-153167-2.jpg",
"calories": 100,
"ingredients_count": 5,
"serve": 1,
"views": 1,
"time": 1,
"translate": {
"post_title": "Chicken Karahi",
"post_description": "spicy and tasteful chicken karahi."
},
"ingredients": [
{
"name": "yogurt",
"quantity": "1 cup",
"image": "https://www.archanaskitchen.com/images/archanaskitchen/BasicRecipes_HOW_TO/How_To_Make_Fresh_Homemade_Yogurt_Curd_400.jpg"
},
{
"name": "red chilli",
"quantity": "100 gram",
"image": "https://ik.imagekit.io/91ubcvvnh3k/tr:w-500/https://www.planetorganic.com//images/products/medium/26148.jpg"
}
]
}
}
Image for refrence
I am facing two errors, which are following,
Another exception was thrown: type '(dynamic) => dynamic' is not a subtype of type '(Ingredient) => Widget' of 'f'
and
type 'Container' is not a subtype of type 'List<Widget>'
In my statefull class I have following
var posts;
bool _load = false;
void initState() {
super.initState();
getRecipeById().then((value) => {
setState((){
posts = value;
})
});
}
and by this method I am getting data from api
getRecipeById() async {
String url = 'http://www.xxxxx.com/xxxxx/in.php';
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': '*/*',
};
final json = {
"by_post_id": 'yes',
"post_id":'${widget.postId}'
};
http.Response response = await http.post(url, body: json);
if(response.statusCode == 200){
setState(() {
_load = true;
});
}
var jsonResponse = jsonDecode(response.body);
posts = RecipeModel.fromJson(jsonResponse['data']);
return posts;
}
Following is my build widget
Widget build(BuildContext context) {
final ingredientsList = Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 1.0, right: 25.0),
margin: const EdgeInsets.only(bottom: 20.0),
child: Container(
child: Column(
children: (_load == false) ? Container(child:Text("loading..")) : posts.ingredients.map<Widget>((data) =>
ingredientsRow(data.name, data.quantity, data.image)
).toList(),
),
),
);
return SafeArea(
top: true,
child: Scaffold(
body: Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child: (_load == false) ? Container(
alignment: Alignment.center,
child: Text("loading now..")
) :
Column(
children: <Widget>[
ingredientsList,
],
),
),
),
)
);
}
and following is function which I want to use in map
ingredientsRow(name, quantity, image)
{
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 2, // 20%
child: Container(
alignment: Alignment.center,
child: Image.network(image,
height: 45,
)
),
),
Expanded(
flex: 4, // 60%
child: Container(
child:Text(
name,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
),
Expanded(
flex: 4, // 20%
child: Container(
alignment: Alignment.center,
child:Text(
quantity,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
)
],
);
}
and here is my data model class
class RecipeModel{
final int id;
final String image;
final List<Ingredient> ingredients;
RecipeModel({this.id, this.image, this.ingredients});
factory RecipeModel.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['ingredients'] as List;
print(list.runtimeType);
List<Ingredient> ingredientsList = list.map((i) => Ingredient.fromJson(i)).toList();
return RecipeModel(
id: parsedJson['id'],
image: parsedJson['image'],
ingredients: ingredientsList
);
}
}
class Ingredient {
final String name;
final String quantity;
final String image;
Ingredient({this.name, this.quantity, this.image});
factory Ingredient.fromJson(Map<String, dynamic> parsedJson){
return Ingredient(
name:parsedJson['name'],
quantity:parsedJson['quantity'],
image:parsedJson['image']
);
}
}
Best way to do this is using a FutureBuilder.
I've checked at your code and changed mainly 4 things:
1- I used an approach with FutureBuilder, which is built for that purpose.
2- Removed ingredientsList variable, and moved the code it to a function named _buildIngredientList with return type Widget.
3- Removed bool variable, because using FutureBuilder it is no longer needed.
4- Added the return type "Widget" to ingredientsRow function, because otherwise it would throw a type error.
Check out the code below:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:stackoverflowsamples/models.dart';
void main() => runApp(
MaterialApp(home: HomePage(),
theme: ThemeData.fallback(),
),
);
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var posts;
///3 - Remove bool
void initState() {
super.initState();
getRecipeById().then((value) => {
setState((){
posts = value;
})
});
}
Widget build(BuildContext context) {
return SafeArea(
top: true,
child: Scaffold(
body: Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child:
FutureBuilder( ///1
future: getRecipeById(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.done) {
return Column(
children: <Widget>[
_buildIngredientList(),
],
);
} else {
return Container(
alignment: Alignment.center,
child: Text("loading now..")
);
}
}
),
),
),
)
);
}
Widget _buildIngredientList() { ///2
return Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 1.0, right: 25.0),
margin: const EdgeInsets.only(bottom: 20.0),
child: Container(
child: Column(
children: posts.ingredients.map<Widget>((data) =>
ingredientsRow(data.name, data.quantity, data.image)
).toList(),
),
),
);
}
///4
Widget ingredientsRow(name, quantity, image) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 2, // 20%
child: Container(
alignment: Alignment.center,
child: Image.network(image,
height: 45,
)
),
),
Expanded(
flex: 4, // 60%
child: Container(
child:Text(
name,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
),
Expanded(
flex: 4, // 20%
child: Container(
alignment: Alignment.center,
child:Text(
quantity,
style: TextStyle(
color: Color(0xff41453c),
fontSize: 15,
fontWeight: FontWeight.w400
),
)
),
)
],
);
}
getRecipeById() async {
///I've pasted the json as literal here because otherwise I couldn't make it run on my side.
var jsonResponse = jsonDecode('''{
"status": true,
"data": {
"id": 1,
"image": "https://img.taste.com.au/fruCLEZM/taste/2019/08/chicken-karahi-153167-2.jpg",
"calories": 100,
"ingredients_count": 5,
"serve": 1,
"views": 1,
"time": 1,
"translate": {
"post_title": "Chicken Karahi",
"post_description": "spicy and tasteful chicken karahi."
},
"ingredients": [
{
"name": "yogurt",
"quantity": "1 cup",
"image": "https://www.archanaskitchen.com/images/archanaskitchen/BasicRecipes_HOW_TO/How_To_Make_Fresh_Homemade_Yogurt_Curd_400.jpg"
},
{
"name": "red chilli",
"quantity": "100 gram",
"image": "https://ik.imagekit.io/91ubcvvnh3k/tr:w-500/https://www.planetorganic.com//images/products/medium/26148.jpg"
}
]
}
}''');
posts = RecipeModel.fromJson(jsonResponse['data']);
return posts;
}
}