Related
i am trying to retrieve data using rest api from woocommerce website using flutter
this is the api for retrieve json data
Future<List<Product>> getProducts(String tagId) async {
List<Product> data = new List<Product>();
try {
String url = Config.url +
Config.productsURL +
"?consumer_key=${Config.key}&consumer_secret=${Config.secret}&tag=$tagId";
var response = await Dio().get(url,
options: new Options(
headers: {HttpHeaders.contentTypeHeader: "application/json"}));
if (response.statusCode == 200) {
data = (response.data as List).map((i) => Product.fromJson(i),).toList();
}
} on DioError catch (e) {
print(e.response);
}
return data;
}
this is the widget to handle the data to the mobile app
class WidgetHomeProducts extends StatefulWidget {
WidgetHomeProducts({Key key, this.labelName, this.tagId}) : super(key : key);
String labelName;
String tagId;
#override
_WidgetHomeProductsState createState() => _WidgetHomeProductsState();
}
class _WidgetHomeProductsState extends State<WidgetHomeProducts> {
APIServices apiServices;
#override
void initState() {
apiServices = new APIServices();
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
color: const Color(0xffF4F7FA),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 16, top: 4),
child: Text(
this.widget.labelName,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
Padding(
padding: EdgeInsets.only(left: 16, top: 4),
child: FlatButton(
onPressed: () {},
child: Text(
'View All',
style: TextStyle(color: Colors.blueAccent),
),
),
),
],
),
_productList(),
],
),
);
}
Widget _productList(){
return new FutureBuilder(
future: apiServices.getProducts(this.widget.tagId),
builder: (BuildContext context, AsyncSnapshot<List<Product>> model){
if(model.hasData){
return _buildList(model.data);
}if(model.hasError){
print("error");
}
return Center(child: CircularProgressIndicator(),);
});
}
i got The method error message that says
'getProducts' was called on null.
Receiver: null
Tried calling: getProducts("971")
can anyone help me to fix this?
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 have been trying to run a flutter app and it keeps giving me Failed assertion error. below is my code. I just want to show the list the second code
class Post extends StatefulWidget {
final String postId;
final String ownerId;
final String username;
final String location;
final String description;
final String mediaUrl;
final dynamic likes;
Post({
this.postId,
this.ownerId,
this.username,
this.location,
this.description,
this.mediaUrl,
this.likes,
});
factory Post.fromDocument(DocumentSnapshot doc) {
return Post(
postId: doc['postId'],
ownerId: doc['ownerId'],
username: doc['username'],
location: doc['location'],
description: doc['description'],
mediaUrl: doc['mediaUrl'],
likes: doc['likes'],
);
}
int getLikeCount(likes) {
// if no likes, return 0
if (likes == null) {
return 0;
}
int count = 0;
// if the key is explicitly set to true, add a like
likes.values.forEach((val) {
if (val == true) {
count += 1;
}
});
return count;
}
#override
_PostState createState() => _PostState(
postId: this.postId,
ownerId: this.ownerId,
username: this.username,
location: this.location,
description: this.description,
mediaUrl: this.mediaUrl,
likes: this.likes,
likeCount: getLikeCount(this.likes),
);
}
class _PostState extends State<Post> {
final String postId;
final String ownerId;
final String username;
final String location;
final String description;
final String mediaUrl;
Int likeCount;
Map likes;
_PostState({
this.postId,
this.ownerId,
this.username,
this.location,
this.description,
this.mediaUrl,
this.likes,
this.likeCount,
});
Widget postingHeading() {
return FutureBuilder(
future:
FirebaseFirestore.instance.collection('User').doc(ownerId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return ListTile(
onTap: () => print('go check the url'),
leading: CircleAvatar(
backgroundImage:
NetworkImage("${snapshot.data.data()['photoUrl']}"),
),
title: Text('${snapshot.data.data()['username']}'),
subtitle: Text(location),
trailing: IconButton(
onPressed: () => print('deleting post'),
icon: Icon(Icons.more_vert),
),
);
});
}
Widget postImagePicture() {
return Stack(
alignment: Alignment.center,
children: [
Image.network(mediaUrl),
],
);
}
Widget postDetailsComment() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
IconButton(icon: Icon(Icons.favorite_border), onPressed: () {}),
IconButton(icon: Icon(Icons.favorite_border), onPressed: () {})
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
"$likeCount likes",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
],
),
Row(
children: [
Text(username),
SizedBox(
width: 1,
),
Flexible(child: Text(description))
],
)
],
);
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
postingHeading(),
postImagePicture(),
postDetailsComment(),
],
);
}
}
here is where I convert it to List... I don't even no what is wrong.... please help.... thanks in advance
class Profile extends StatefulWidget {
final String currentUser;
Profile({this.currentUser});
#override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
final _firestore = FirebaseFirestore.instance;
int postLenght;
List<Post> post;
bool pleaseWait;
#override
void initState() {
super.initState();
getUsersPicsDetails();
}
getUsersPicsDetails() async {
setState(() {
pleaseWait = false;
});
QuerySnapshot _getPost = await _firestore
.collection('post')
.doc(widget.currentUser)
.collection('userPost')
.orderBy('timeStamp', descending: true)
.get();
setState(() {
pleaseWait = true;
postLenght = _getPost.docs.length;
post = _getPost.docs.map((e) => Post.fromDocument(e)).toList();
print(postLenght);
});
}
fellowEditButtton({String test, Function press}) {
return TextButton(
onPressed: press,
child: Container(
alignment: Alignment.center,
height: 25,
width: 250,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
border: Border.all(),
borderRadius: BorderRadius.circular(8.0)),
child: Text(
test,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
)),
);
}
gettingUserprofile() {
return StreamBuilder(
stream: _firestore.collection('User').doc(widget.currentUser).snapshots(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.connectionState != ConnectionState.active) {
return Text('this stuff en');
}
return ListView.builder(
itemCount: 1,
itemBuilder: (context, index) => Container(
padding: EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
FullScreenWidget(
child: Hero(
tag: 'smallImage',
child: CircleAvatar(
backgroundImage: NetworkImage(
'${snapshot.data.data()['photoUrl']}'),
radius: 50.0,
),
),
),
Expanded(
flex: 1,
child: Column(
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
topColum(buttom: 'Post', number: 1),
topColum(buttom: 'Fellowers', number: 2),
topColum(buttom: 'Following', number: 0),
],
),
Column(
crossAxisAlignment:
CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: widget.currentUser ==
_auth.currentUser.uid
? fellowEditButtton(
test: 'Edit Profile',
press: profileEditingButton)
: fellowEditButtton(
test: 'Fellow', press: () {})),
],
),
],
),
),
],
),
Divider(),
//! this is i call the list
//getUserPicture(),
getUserPicture(),
],
),
));
},
);
}
profileEditingButton() {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => EditProfile(
userProfile: widget.currentUser,
)));
}
Widget topColum({int number, String buttom}) {
return Column(
children: [
Text(
'$number',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Text(
buttom,
style: TextStyle(
fontSize: 20,
),
),
],
);
}
//! this is the where i return the list
Widget getUserPicture() {
if (pleaseWait = false) {
return CircularProgressIndicator();
}
return Column(
children: post,
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: header(context, titleString: "Profile"),
body:
//Text('${widget.currentUser}')
gettingUserprofile());
// userPictursPost(),
}
}
I want to the get the post at the bottom... thanks in advance
below is the error image
enter image description here
When you get an error, please post it along with your question. When you are getting an error, it means that something is wrong with your code,and most likely not the flutter engine. Both are important for debugging, the error+your code.
Try changing this
QuerySnapshot _getPost = await _firestore
.collection('post')
.doc(widget.currentUser)
.collection('userPost')
.orderBy('timeStamp', descending: true)
.get();
setState(() {
pleaseWait = true;
postLenght = _getPost.docs.length;
post = _getPost.docs.map((e) => Post.fromDocument(e)).toList();
print(postLenght);
});
into this:
QuerySnapshot _getPost = await _firestore
.collection('post')
.doc(widget.currentUser)
.collection('userPost')
.orderBy('timeStamp', descending: true)
.get();
if(_getPost.docs.isNotEmpty){
List<Post> tempPost = _getPost.docs.map((e) => Post.fromDocument(e)).toList();
setState(() {
pleaseWait = true;
post =tempPost
print(postLenght);
});
}else{
print('The List is empty);}
You are not checking if the Query result has data or not. If it's empty, you will pass an empty List post down your tree, and you will get the error you are having.
For people facing similar issues, let me tell what I found in my code:
The error says that the children is null, not empty !
So if you are getting the children for the parent widget like Row or Column from a separate method, just check if you are returning the constructed child widget from the method.
Row(
children: getMyRowChildren()
)
.
.
.
getMyRowChildren(){
Widget childWidget = ... //constructed
return childWidget; //don't forget to return!
}
Else it would return null, which results in the children being null and we get the mentioned above error!
Good afternoon, I have a problem that I have already tried to solve on my own for days, but I can not, I hope you can help me.
I have 2 DropdownButton, of which the first one if it changes and the next one loads. When I try to change the second DropdownButton, let's say I choose ACCESSORIES I get the message, lines below I attach the code.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:app_calimod_pedidos/models/coleccion.dart';
import 'package:app_calimod_pedidos/providers/coleccion_provider.dart';
import 'package:app_calimod_pedidos/providers/compania_provider.dart';
import 'package:app_calimod_pedidos/services/coleccion_services.dart';
import 'package:app_calimod_pedidos/shared_preference/usuario_shared_preference.dart';
import 'package:app_calimod_pedidos/models/compania.dart';
import 'package:app_calimod_pedidos/models/usuario.dart';
import 'package:app_calimod_pedidos/providers/usuario_provider.dart';
import 'package:app_calimod_pedidos/services/compania_services.dart';
dynamic tempColeccionSelect;
class ProductosPage extends StatefulWidget {
const ProductosPage({Key key}) : super(key: key);
#override
_ProductosPageState createState() => _ProductosPageState();
}
class _ProductosPageState extends State<ProductosPage> {
List<Compania> _companialist;
Compania _compania;
Coleccion _coleccion;
CompaniaServices _companiaServices = new CompaniaServices();
ColeccionServices _coleccionServices = new ColeccionServices();
UsuarioPreferences _usuarioPreferences = new UsuarioPreferences();
String token;
List<Compania> listcompania;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
Compania selectCompania;
Usuario usuario = Provider.of<UsuarioProvider>(context).getUsuario;
token = usuario.token;
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Pedidos'),
),
body: Container(
padding: EdgeInsets.all(15.0),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Center(
child: Text(
'PEDIDO',
style: TextStyle(
fontSize: 17.0,
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Column(
children: [
ListarCombos(
token: token,
)
],
))
],
)
],
),
),
),
);
}
}
class ListarCombos extends StatefulWidget {
final String token;
ListarCombos({#required this.token});
#override
_ListarCombosState createState() => _ListarCombosState();
}
class _ListarCombosState extends State<ListarCombos> {
CompaniaServices companiaServices = new CompaniaServices();
ColeccionServices coleccionServices = new ColeccionServices();
List<Compania> listcompania;
List<Coleccion> listcoleccion;
Compania selectCompania;
Coleccion _selectColeccion;
String selectCombo;
#override
Widget build(BuildContext context) {
final coleccionProvider =
Provider.of<ColeccionProvider>(context, listen: false);
return Container(
//width: MediaQuery.of(context).size.width * 0.7,
child: Column(
children: [
FutureBuilder(
// future: companiaServices.obtenerCompania(widget.token),
future: companiaServices.obtenerCompania(widget.token),
builder: (context, AsyncSnapshot snaphost) {
if (snaphost.hasData) {
listcompania = snaphost.data;
return Container(
child: DropdownButton<Compania>(
hint: Text("Seleccionar"),
value: selectCompania,
onChanged: (Compania value) {
setState(() {
selectCompania = value;
Provider.of<CompaniaProvider>(context,
listen: false)
.setCompania(value);
});
},
items: listcompania.map((Compania compania) {
return new DropdownMenuItem<Compania>(
value: compania,
child: new Text(
compania.name,
style: new TextStyle(color: Colors.black),
),
);
}).toList()));
} else {
return Container(child: CircularProgressIndicator());
}
}),
//selectCompania != null ??
SizedBox(
height: 10,
),
selectCompania != null
? FutureBuilder(
future: coleccionServices.obtenerColeccion(
widget.token, selectCompania.id),
builder: (context, AsyncSnapshot snaphost) {
if (snaphost.connectionState == ConnectionState.waiting) {
return Container(
child: CircularProgressIndicator(),
);
}
if (snaphost.hasData) {
listcoleccion = null;
listcoleccion = snaphost.data;
return DropdownButton<Coleccion>(
value: _selectColeccion,
hint: Text('Seleccione'),
onChanged: (Coleccion value) {
setState(() {
_selectColeccion = value;
});
},
items: listcoleccion?.map((Coleccion coleccion) {
return new DropdownMenuItem<Coleccion>(
value: coleccion,
child: new Text(
coleccion.name,
style: new TextStyle(color: Colors.black),
),
);
})?.toList() ??
[]);
} else {
return Container(
child: Text('Seleccione una Compania'),
);
}
})
: Container(
child: Text('ABC'),
)
],
),
);
}
}
https://gist.github.com/hacrispin/162345a2a3ee4953c96c41dbe69f47bd
Imagen ERROR APP
Imagen Error
Image is not coming but all the data in the firebase database is showing in the app.
import 'package:flutter/material.dart';
import 'Authentication.dart';
import 'photoUpload.dart';
import 'Posts.dart';
import 'package:firebase_database/firebase_database.dart';
// import 'package:flutter_blogapp/Authentication.dart';
// import 'package:flutter_blogapp/photoUpload.dart';
class HomePage extends StatefulWidget
{
HomePage
(
{
this.auth,
this.onSignedOut,
}
);
final AuthImplementation auth;
final VoidCallback onSignedOut;
#override
State<StatefulWidget> createState()
{
return _HomePageState();
}
}
class _HomePageState extends State<HomePage>
{
List<Posts> postsList = [];
#override
void initState()
{
super.initState();
DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");
postsRef.once().then((DataSnapshot snap)
{
var KEYS = snap.value.keys;
var DATA = snap.value;
postsList.clear();
for(var individualKey in KEYS)
{
Posts posts = new Posts
(
DATA[individualKey]['image'],
DATA[individualKey]['description'],
DATA[individualKey]['data'],
DATA[individualKey]['time'],
);
postsList.add(posts);
}
setState(()
{
print('Length : $postsList.length');
});
});
}
void _logoutUser() async
{
try
{
await widget.auth.signOut();
widget.onSignedOut();
}
catch (e)
{
print(e.toString());
}
}
#override
Widget build(BuildContext context)
{
return new Scaffold
(
appBar: new AppBar
(
title: new Text('Home'),
),
body : new Container
(
child: postsList.length == 0 ? new Text(" No Post available ") : new ListView.builder
(
itemCount: postsList.length,
itemBuilder: (_, index)
//itemBuilder: (BuildContext _, int index ) //<-----
{
return PostsUI(postsList[index].image, postsList[index].description, postsList[index].date, postsList[index].time);
}
),
),
bottomNavigationBar: new BottomAppBar
(
color: Colors.pink,
child: new Container
(
margin: const EdgeInsets.only(left: 70.0, right: 70.0),
child: new Row
(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: <Widget>
[
new IconButton
(
icon: new Icon(Icons.local_car_wash),
iconSize: 50,
color: Colors.white,
onPressed: _logoutUser,
),
new IconButton
(
icon: new Icon(Icons.add_a_photo),
iconSize: 50,
color: Colors.white,
onPressed: ()
{
Navigator.push
(
context,
MaterialPageRoute(builder: (context)
{
return new UploadPhotoPage();
})
);
},
),
],
),
),
),
);
}
// Designing Posts UI
Widget PostsUI(String image, String description, String date, String time)
{
return new Card
(
elevation: 10.0,
margin: EdgeInsets.all(15.0),
child: new Container
(
padding: new EdgeInsets.all(14.0),
child: new Column
(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>
[
new Row
(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>
[
new Text
(
date,
style: Theme.of(context).textTheme.subtitle,
textAlign: TextAlign.center,
),
new Text
(
time,
style: Theme.of(context).textTheme.subtitle,
textAlign: TextAlign.center,
), //<----
],
),
SizedBox(height: 10.0,),
new Image.network(image, fit:BoxFit.cover),
SizedBox(height: 10.0,),
new Text
(
description,
style: Theme.of(context).textTheme.subhead,
textAlign: TextAlign.center,
),
],
)
)
);
}
}
The following errors are showing:
═══════ Exception caught by image resource service
════════════════════════════ The following ArgumentError was thrown
resolving an image codec: Invalid argument(s): No host specified in
URI file:///image
When the exception was thrown, this was the stack
0 _HttpClient._openUrl (dart:_http/http_impl.dart:2276:9)
1 _HttpClient.getUrl (dart:_http/http_impl.dart:2197:48)
2 NetworkImage._loadAsync package:flutter/…/painting/_network_image_io.dart:84
3 NetworkImage.load package:flutter/…/painting/_network_image_io.dart:47
4 ImageProvider.resolve...
package:flutter/…/painting/image_provider.dart:327 ... Image provider:
NetworkImage("image", scale: 1.0) Image key: NetworkImage("image",
scale: 1.0)
The main part of the error message is:
Invalid argument(s): No host specified in URI file:///image
From this it looks like you're storing a local file:/// reference into the database, instead of a globally accessible URL (typically starting with http:// or https://).
The solution is in the code that writes to the database, to actually upload the image to a public storage place (such as to Firebase Storage) and then write the resulting download URL into the database.