FutureBuilder<List> is not displaying any data - android

I am writing a flutter app that is listing the whole players of a card game. And if no players are inside the database, then there should be a text that is saying, that is no data found. But my problem is inside the getStatistik(). That function is returning no data.
This is my code where I want to display the player in sort of a ranking:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:watten/model/statistik.dart';
import 'package:watten/database/database.dart';
import 'package:watten/statistik/deleteStatistikDialog.dart';
Future<List<Statistik>> fetchStatistik() async{
var dbHelper = DBHelper();
List<Statistik> statistik = await dbHelper.getStatistik();
print("Length: "+statistik.length.toString()");
return statistik;
}
class Spielerstatistik extends StatefulWidget{
#override
State<StatefulWidget> createState() => _Spielerstatistik();
}
class _Spielerstatistik extends State<Spielerstatistik>{
List statistik;
var dbHelper = DBHelper();
bool datenVorhanden = true;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
backgroundColor: Color(0xFF9C27B0),
title: new Text("Ranking")
),
body: new FutureBuilder<List<Statistik>>(
future: fetchStatistik(),
builder: (context, snapshot){
if(snapshot.hasData){
return new Column(
children: <Widget>[
new Expanded(
child: new ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return new Card(
color: Colors.red,
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: platzNr
? platzierung
: new Text(" ${index+1}"),
title: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
child: new Text(
snapshot.data[index].name,
style: TextStyle(color: Colors.black),
overflow: TextOverflow.ellipsis,
),
width: 80.0,
),
new Padding(padding: EdgeInsets.only(left: 45.0)),
new Container(
child: new Text(
snapshot.data[index].spielanzahl.toString(),
style: TextStyle(color: Colors.black),
overflow: TextOverflow.ellipsis,
),
width: 55.0,
),
new Container(
decoration: new BoxDecoration(
border: new Border(
left: BorderSide(color: Colors.black26)
)
),
height: 40.0,
margin: EdgeInsets.only(right: 22.0),
),
new Container(
child: new Text(
snapshot.data[index].gewonneneSpiele.toString(),
style: TextStyle(color: textfarbe),
overflow: TextOverflow.ellipsis,
),
width: 12.0,
margin: EdgeInsets.only(right: 20.0),
),
new Container(
decoration: new BoxDecoration(
border: new Border(
left: BorderSide(color: Colors.black26)
)
),
height: 40.0,
margin: EdgeInsets.only(right: 8.0),
),
new Container(
child: new Text(
snapshot.data[index].erfolgsquote.roundToDouble().toString() + " %",//Erfolgsquote
style: TextStyle(color: Colors.black),
overflow: TextOverflow.ellipsis,
),
width: 65.0,
),
],
)
)
],
),
);
}
)
)
],
);
} else if(snapshot.data.length == 0){
return new Text("No Data found!");
}
return new Container(alignment: AlignmentDirectional.center,child: new CircularProgressIndicator(),);
}
),
);
}
}
And this is my code where I get the data for the database from:
Future<List<Statistik>> getStatistik() async{
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM statistik');
List<Statistik> statistik = new List();
for(int i = 0; i<list.length; i++){
statistik.add(new Statistik(name: list[i]["$statistikName"] , spielanzahl: list[i]["$statistikSpielanzahl"], gewonneneSpiele: list[i]["$statistikWins"], erfolgsquote: list[i]["erfolgsquote"]));
}
return statistik;
}
My thoughts are that the FutureBuilder is not even making a real call, because print("Length: "+statistik.length.toString()"); that I built in, wasn't printing anything.

when snapshot.hasData is false, snapshot.data equals null. Therefore you can't do
if (snapshot.hasData) {} else if (snapshot.data.length > 0) {}
Instead just do a if (snapshot.hasData == false)

I think that there is no need to use $. Try the below code snippet. It is explained here in detail.
Future<List<Statistik>> getStatistik() async{
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM statistik');
List<Statistik> statistik = new List();
for(int i = 0; i<list.length; i++){
statistik.add(new Statistik(name: list[i]["statistikName"] , spielanzahl: list[i]["statistikSpielanzahl"], gewonneneSpiele: list[i]["statistikWins"], erfolgsquote: list[i]["erfolgsquote"]));
}
return statistik;
}

Related

Flutter DragTarget onAccept is not being called

I am developing a feature where the user enters a sentence, in the next screen the words of that sentence get shuffled randomly, then the user has to drag the words to a drag target to form the original sentence.
You can get an idea from the screenshots below.
First screen
Second screen
Now the problem I am having is, when dragging the words to the target I can see the DragTarget is calling onWillAccept as I added a print() statement there, if it is doing so then it should call onAccept eventually but it is not doing so. This is why my codes that deal with Bloc are not getting called and the words are not showing up in the target spot.
Code
class SentenceMakeScreen extends StatefulWidget {
String inputSentence;
SentenceMakeScreen(this.inputSentence);
#override
State<SentenceMakeScreen> createState() => _SentenceMakeScreenState();
}
class _SentenceMakeScreenState extends State<SentenceMakeScreen> {
List<String> sentence = [];
List<Widget> wordWidgets = [];
bool isDragSuccessful = false;
final ButtonStyle _buttonStyle = ElevatedButton.styleFrom(
textStyle: TextStyle(fontSize: 20)
);
_getTextWidgets(List<String> sentence) {
for(var i = 0; i < sentence.length; i++){
wordWidgets.add(
Draggable<WordWidget>(
data: WordWidget(sentence[i]),
child: WordWidget(sentence[i]),
feedback: WordWidget(sentence[i]),
childWhenDragging: Container(),
)
);
}
}
_randomlyOrganizeSentence(String inputString) {
sentence = inputString.split(new RegExp(r" "));
sentence.shuffle();
print(sentence);
}
#override
void initState() {
// TODO: implement initState
_randomlyOrganizeSentence(widget.inputSentence);
_getTextWidgets(sentence);
super.initState();
}
#override
Widget build(BuildContext context) {
final _dragDropBloc = DragDropBloc();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
),
body: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
DragTarget<WordWidget>(
builder: (context, data, rejectedData) {
return Center(
child: this.isDragSuccessful
?
Container(
width: double.maxFinite,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(width: 1.0, color: Colors.black),
),
),
child: StreamBuilder<List<WordWidget>>(
stream: _dragDropBloc.widgetStream,
initialData: [],
builder: (BuildContext context, AsyncSnapshot<List<WordWidget>> snapshot) {
print("Here ${snapshot.data}");
return Wrap(
direction: Axis.horizontal,
children: [
//correctly ordered words
],
);
},
),
)
:
Container(
width: double.maxFinite,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(width: 1.0, color: Colors.black),
),
),
child: Text("Drag here")
),
);
},
onWillAccept: (data) {
print("true");
return true;
},
onAccept: (data) {
print(data.toString());
_dragDropBloc.dragDropEventSink.add(
DropEvent(WordWidget(data.toString()))
);
setState(() {
this.isDragSuccessful = true;
//draggedWords.add(data.toString());
});
},
),
Wrap(
direction: Axis.horizontal,
children: wordWidgets
),
Container(
child: ElevatedButton(
style: _buttonStyle,
onPressed: () {
},
child: Text("Check"),
),
),
],
),
),
);
}
}
WordWidget
import 'package:flutter/material.dart';
class WordWidget extends StatelessWidget {
final String word;
const WordWidget(this.word);
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.red[900],
border: Border.all(
width: 4,
color: Colors.black
),
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: EdgeInsets.all(5),
child: Text(
word,
style: TextStyle(
color: Colors.white
),
)
),
);
}
}
I tried adding the type of data I am passing from Draggable to DragTarget, this is what was advised here. It did not work.
I was also getting the same error earlier today. I then upgraded my flutter to the latest version and wrote the DragTarget code again from scratch. I don't know what worked for me but you can try doing the same.

Flutter- Can border radius be given to Expansion Panel list? If yes, what are the properties that should be used

I have this code for expansion panel list which is working fine but I am not able to extend the size of the expansion panel. Also, I want the expansion panel to have a border radius but I am not sure if border radius can be given
return Column(children: [
Stack(
clipBehavior: Clip.none,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 50),
child: ExpansionPanelList(
animationDuration: Duration(milliseconds: 1000),
children: [
ExpansionPanel(
headerBuilder: (context, isExpanded) {
return Column(
children: [
Text("Salmon Poké"),
Text("Rs. 2000"),
],
);
},
body: Text(
'This salmon sashimi is a delicious light appetizer served with fresh wasabi, ginger, soy sauce or a delicious side of soy yuzo citrus ponzu.',
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
isExpanded: _expanded,
canTapOnHeader: true,
backgroundColor: Colors.white),
],
dividerColor: Colors.grey,
expansionCallback: (panelIndex, isExpanded) {
_expanded = !_expanded;
setState(() {});
},
),
),
Positioned(
top: -55,
right: 240,
child: CircleAvatar(
radius: 105,
child: ClipOval(
child: Image(
image: AssetImage('assets/images/salmon.png'),
),
),
backgroundColor: Colors.transparent,
),
),
],
),
]);
}
}
**Here is the UI for the given code **
This is the output I have.
Here is the output which I want. (This UI is made using container widgets but I want this layout using expansion panel list)
This is the output that I want
I really appreciate your help.
For border radius we need to make custom expansion list
import 'package:flutter/material.dart';
const double _kPanelHeaderCollapsedHeight = 48.0;
const double _kPanelHeaderExpandedHeight = 64.0;
class CustomExpansionPanelList extends StatelessWidget {
const CustomExpansionPanelList(
{Key key,
this.children: const <ExpansionPanel>[],
this.expansionCallback,
this.animationDuration: kThemeAnimationDuration})
: assert(children != null),
assert(animationDuration != null),
super(key: key);
final List<ExpansionPanel> children;
final ExpansionPanelCallback expansionCallback;
final Duration animationDuration;
bool _isChildExpanded(int index) {
return children[index].isExpanded;
}
#override
Widget build(BuildContext context) {
final List<Widget> items = <Widget>[];
const EdgeInsets kExpandedEdgeInsets = const EdgeInsets.symmetric(
vertical: _kPanelHeaderExpandedHeight - _kPanelHeaderCollapsedHeight);
for (int index = 0; index < children.length; index += 1) {
if (_isChildExpanded(index) && index != 0 && !_isChildExpanded(index - 1))
items.add(new Divider(
key: new _SaltedKey<BuildContext, int>(context, index * 2 - 1),
height: 15.0,
color: Colors.transparent,
));
final Row header = new Row(
children: <Widget>[
new Expanded(
child: new AnimatedContainer(
duration: animationDuration,
curve: Curves.fastOutSlowIn,
margin: _isChildExpanded(index)
? kExpandedEdgeInsets
: EdgeInsets.zero,
child: new SizedBox(
height: _kPanelHeaderCollapsedHeight,
child: children[index].headerBuilder(
context,
children[index].isExpanded,
),
),
),
),
new Container(
margin: const EdgeInsetsDirectional.only(end: 8.0),
child: new ExpandIcon(
isExpanded: _isChildExpanded(index),
padding: const EdgeInsets.all(16.0),
onPressed: (bool isExpanded) {
if (expansionCallback != null)
expansionCallback(index, isExpanded);
},
),
),
],
);
double _radiusValue = _isChildExpanded(index)? 8.0 : 0.0;
items.add(
new Container(
key: new _SaltedKey<BuildContext, int>(context, index * 2),
child: new Material(
elevation: 2.0,
borderRadius: new BorderRadius.all(new Radius.circular(_radiusValue)),
child: new Column(
children: <Widget>[
header,
new AnimatedCrossFade(
firstChild: new Container(height: 0.0),
secondChild: children[index].body,
firstCurve:
const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
secondCurve:
const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
sizeCurve: Curves.fastOutSlowIn,
crossFadeState: _isChildExpanded(index)
? CrossFadeState.showSecond
: CrossFadeState.showFirst,
duration: animationDuration,
),
],
),
),
),
);
if (_isChildExpanded(index) && index != children.length - 1)
items.add(new Divider(
key: new _SaltedKey<BuildContext, int>(context, index * 2 + 1),
height: 15.0,
));
}
return new Column(
children: items,
);
}
}
class _SaltedKey<S, V> extends LocalKey {
const _SaltedKey(this.salt, this.value);
final S salt;
final V value;
#override
bool operator ==(dynamic other) {
if (other.runtimeType != runtimeType) return false;
final _SaltedKey<S, V> typedOther = other;
return salt == typedOther.salt && value == typedOther.value;
}
#override
int get hashCode => hashValues(runtimeType, salt, value);
#override
String toString() {
final String saltString = S == String ? '<\'$salt\'>' : '<$salt>';
final String valueString = V == String ? '<\'$value\'>' : '<$value>';
return '[$saltString $valueString]';
}
}
Now use this widget in your application
import 'package:color_essence/customViews/CustomExpansionList.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class ExpansionPanelDemo extends StatefulWidget {
#override
_ExpansionPanelDemoState createState() => _ExpansionPanelDemoState();
}
class _ExpansionPanelDemoState extends State<ExpansionPanelDemo> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Expansion Panel Demo'),
),
body: Container(
padding: EdgeInsets.all(10),
child: ListView.builder(
itemCount: itemData.length,
itemBuilder: (BuildContext context, int index) {
return CustomExpansionPanelList(
animationDuration: Duration(milliseconds: 1000),
children: [
ExpansionPanel(
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
padding: EdgeInsets.all(10),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ClipOval(
child: CircleAvatar(
child: Image.asset(
itemData[index].img,
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 30,
),
Text(
itemData[index].discription,
style: TextStyle(
color: Colors.grey[700],
fontSize: 15,
letterSpacing: 0.3,
height: 1.3),
),
],
),
),
headerBuilder: (BuildContext context, bool isExpanded) {
return Container(
padding: EdgeInsets.all(10),
child: Text(
itemData[index].headerItem,
style: TextStyle(
color: itemData[index].colorsItem,
fontSize: 18,
),
),
);
},
isExpanded: itemData[index].expanded,
)
],
expansionCallback: (int item, bool status) {
setState(() {
itemData[index].expanded = !itemData[index].expanded;
});
},
);
},
),
),
);
}
List<ItemModel> itemData = <ItemModel>[
ItemModel(
headerItem: 'Android',
discription:
"Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. ... Some well known derivatives include Android TV for televisions and Wear OS for wearables, both developed by Google.",
colorsItem: Colors.green,
img: 'assets/images/android_img.png'
),
];
}
class ItemModel {
bool expanded;
String headerItem;
String discription;
Color colorsItem;
String img;
ItemModel({this.expanded: false, this.headerItem, this.discription,this.colorsItem,this.img});
}
Wrap the ExpansionPanelList in a ClipRRect.
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: ExpansionPanelList(
children: [ExpansionPanel(body: Text('Hello World'))])
)

Red Screen Error type 'String' is not a subtype of type 'int' of 'index' Flutter

When I navigate my chat page, I see this error in red screen on emulator.
No idea why it does not work. Does anyone know how to solve it?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../chat/chat.dart';
class ChatHome extends StatefulWidget {
#override
_ChatHomeState createState() => _ChatHomeState();
}
class _ChatHomeState extends State<ChatHome> {
var _db = FirebaseFirestore.instance;
TextEditingController userController;
final _scaffKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
userController = new TextEditingController();
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffKey,
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
// barrierDismissible: false,
context: context,
builder: (context) => _buildPopUpMessage(context),
);
},
splashColor: Theme.of(context).colorScheme.onSecondary,
child: Icon(
Icons.add,
),
),
body: FutureBuilder(
future: getPosts(),
builder: (_, snapshot) {
if (snapshot.hasData) {
String myId = snapshot.data['id'];
return StreamBuilder(
stream: getChats(myId),
builder: (context, snapshot) {
if (snapshot.hasData) {
QuerySnapshot qSnap = snapshot.data;
List<DocumentSnapshot> docs = qSnap.docs;
if (docs.length == 0)
return Center(
child: Text('No Chats yet!'),
);
return ListView.builder(
itemCount: docs.length,
itemBuilder: (context, index) {
List<dynamic> members = docs[index].data()['members'];
String userId;
userId = members.elementAt(0) == myId
? members.elementAt(1)
: members.elementAt(0);
return FutureBuilder(
future: getUserByUsername(userId),
builder: (context, _snapshot) {
if (_snapshot.hasData) {
DocumentSnapshot docSnapUser = _snapshot.data;
Map<String, dynamic> _user = docSnapUser.data();
return Card(
margin: EdgeInsets.all(8.0),
elevation: 8.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: InkWell(
splashColor:
Theme.of(context).colorScheme.primary,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: _user["id"],
peerAvatar: _user['photoUrl'],
))),
child: Container(
margin: EdgeInsets.all(10.0),
height:
MediaQuery.of(context).size.height * 0.08,
child: Center(
child: Row(
children: [
Hero(
tag: _user['photoUrl'],
child: Container(
width: MediaQuery.of(context)
.size
.width *
0.15,
height: MediaQuery.of(context)
.size
.width *
0.15,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.cover,
image: new NetworkImage(
_user['photoUrl']),
),
),
),
),
SizedBox(
width: MediaQuery.of(context)
.size
.width *
0.02,
),
SizedBox(
width: MediaQuery.of(context)
.size
.width *
0.43,
child: Text(
_user['nickname'],
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
),
);
}
return Card(
margin: EdgeInsets.all(8.0),
elevation: 8.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Container(
margin: EdgeInsets.all(10.0),
height: MediaQuery.of(context).size.height * 0.08,
child: Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation(
Theme.of(context).colorScheme.primary,
),
),
),
),
);
},
);
},
);
}
return Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation(
Theme.of(context).colorScheme.primary,
),
),
);
},
);
}
return Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation(
Theme.of(context).colorScheme.primary,
),
),
);
},
),
);
}
Widget _timeDivider(Timestamp time) {
DateTime t = time.toDate();
String minute =
t.minute > 9 ? t.minute.toString() : '0' + t.minute.toString();
String ampm = t.hour >= 12 ? "PM" : "AM";
int hour = t.hour >= 12 ? t.hour % 12 : t.hour;
DateTime press = DateTime.now();
if (press.year == t.year && press.month == t.month && press.day == t.day)
return Text(hour.toString() + ':' + minute + ' ' + ampm);
return Text(t.day.toString() +
'/' +
(t.month + 1).toString() +
'/' +
t.year.toString());
}
Widget _buildPopUpMessage(context) {
return Align(
alignment: Alignment.topCenter,
child: Container(
padding: EdgeInsets.all(8.0),
height: MediaQuery.of(context).size.width * .5,
width: MediaQuery.of(context).size.width * .6,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(40),
),
margin: EdgeInsets.only(bottom: 50, left: 12, right: 12, top: 50),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.width * .1,
child: Center(
child: new RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: 'username',
style: new TextStyle(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.bold),
),
new TextSpan(
text: '#gmail.com',
),
],
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.width * .2,
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Material(
child: TextField(
autofocus: true,
controller: userController,
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
),
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
),
focusedBorder: new OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
),
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
),
enabledBorder: new OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
),
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
),
errorBorder: new OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.error,
),
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
),
filled: true,
hintText: "Type in only Username",
hintStyle: TextStyle(fontSize: 16.0),
),
),
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.width * .1,
child: Center(
child: Align(
alignment: Alignment.center,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
color: Theme.of(context).colorScheme.secondary,
child: Text(
'Let\'s chat with your friend.',
style: TextStyle(
color: Theme.of(context).colorScheme.onSecondary),
),
onPressed: () async {
if (userController.text.isNotEmpty) {
String username = userController.text.toString();
userController.clear();
QuerySnapshot doc =
getUserByEmail(username + '#gmail.com');
if (doc.docs.length != 0) {
DocumentSnapshot user = doc.docs[0];
Map<String, dynamic> userData = user.data();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: userData["id"],
peerAvatar: userData['photoUrl'],
)));
print(user.data()['nickname'].toString());
} else {
showSnackPlz(context, username);
Navigator.pop(context);
}
} else {
showSnackPlzWithMessage(context, 'Empty Username');
Navigator.pop(context);
}
},
),
),
),
),
],
),
),
),
);
}
showSnackPlz(BuildContext context, String username) {
final SnackBar snackMe = SnackBar(
content: new RichText(
text: new TextSpan(
style: new TextStyle(
fontSize: 14.0,
),
children: <TextSpan>[
new TextSpan(
text: 'User with email ',
),
new TextSpan(
text: username,
style: new TextStyle(fontWeight: FontWeight.bold),
),
new TextSpan(
text: '#gmail.com not in the database!',
),
],
),
),
);
_scaffKey.currentState.showSnackBar(snackMe);
}
showSnackPlzWithMessage(BuildContext context, String message) {
final SnackBar snackMe = SnackBar(
content: new Text(message),
);
_scaffKey.currentState.showSnackBar(snackMe);
}
getChats(String uid) {
return FirebaseFirestore.instance
.collection('messages')
.where('members', arrayContains: uid)
.snapshots();
}
getUserByUsername(String username) async {
return await _db.collection('users').doc(username).get();
}
getUserByEmail(String email) async {
return await _db.collection('users').where('email', isEqualTo: email).get();
}
Future getPosts() async {
var firestore = FirebaseFirestore.instance;
QuerySnapshot qn = await firestore.collection('users').get();
return qn.docs;
}
}
Can't find which code-row causes this.
Tried many changes but nothing helped.
Screenshot of the error
I've been facing this problem for whole day. Being rookie in flutterworld sometimes take bunch of time.
I can only assume what the problem could be please send the logs... So
List<dynamic> members = docs[index].data()['members'];
String userId;
userId = members.elementAt(0) == myId
? members.elementAt(1)
: members.elementAt(0);
You are using this to get the userId (String) from a dynamic list.
check whether you dynamic list only contains String values before handling a value as a string. Please do this for all other occurrences of dynamic...
This error means that you cast an int to a string. That is illegal. Just check all your String occurrences.

Flutter: i get invalid argument(s) Error in flutter if i want to navigate to detail page

I want to navigate to detail page. But i get invalid argument error. In detail page, i try to get detail information from my online server. If i click on Hot reload button in android studio, the error disappear. Please, How can i do to fix this error ? Screenshoot of error
the error log :
════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
Invalid argument(s): The source must not be null
The relevant error-causing widget was:
DetailArticlePage file:///C:/Users/abiboo/FlutterProject/projectname/lib/miledoo_widget/home.dart:515:39
//home.dart
return new Container(
margin: EdgeInsets.symmetric(vertical: 8.0),
height: 240.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: articledata.length,
itemBuilder: (BuildContext context,int index) {
return Padding(
padding: EdgeInsets.all(4),
child: InkWell(
onTap: (){
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailArticlePage(int.parse(articledata[index].idArt), articledata[index].designation)));
},
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
This is a piece of code for detail page who contain a method to get detail informaation from server
//detailpage.dart
import 'package:cached_network_image/cached_network_image.dart';
import 'package:f_miledoo/miledoo_widget/detail_boutique_page.dart';
import 'package:f_miledoo/miledoo_widget/panier_page.dart';
import 'package:f_miledoo/models/detail_article_models.dart';
import 'package:f_miledoo/models/panier_models.dart';
import 'package:f_miledoo/shared/constants.dart';
import 'package:f_miledoo/utils/database_helper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../localisation_internationnalisation/localisation.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
class DetailArticlePage extends StatefulWidget{
final int id_art;
final String art_desgnation;
DetailArticlePage(this.id_art, this.art_desgnation);
DetailArticlePages createState() => DetailArticlePages();
}
class DetailArticlePages extends State<DetailArticlePage> {
DatabaseHelper helper = DatabaseHelper();
PanierModel _panier = new PanierModel.withempty();
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
int qtecompter = 1;
double prixTotal = 0.0;
String aAfficher = "";
int taillePanier = 0;
String idArt;
String designation;
String descrip;
String prixUnit;
String prixUnit2;
String qteStock;
String idBou;
String lienPhoto;
String nomBou;
#override
void initState() {
// TODO: implement initState
super.initState();
getpanierTaille();
this.getRecapArticleData(widget.id_art, widget.art_desgnation);
}
getpanierTaille() async => taillePanier = await helper.getCount();
getRecapArticleData(int id_article, String nom_article) async {
final response = await http.get(BASE + "xxxxxxx?id_art="+ id_article.toString() +"&nom_art="+ nom_article);
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
TheDetailData myData = new TheDetailData.fromJson(jsonResponse);
for (var i = 0; i < myData.articledetail.list_recap_article.length; i++) {
idArt = myData.articledetail.list_recap_article[i].idArt;
designation = myData.articledetail.list_recap_article[i].designation;
descrip = myData.articledetail.list_recap_article[i].descrip;
prixUnit = myData.articledetail.list_recap_article[i].prixUnit;
prixUnit2 = myData.articledetail.list_recap_article[i].prixUnit2;
qteStock = myData.articledetail.list_recap_article[i].qteStock;
lienPhoto = myData.articledetail.list_recap_article[i].lienPhoto;
idBou = myData.articledetail.list_recap_article[i].idBou;
print("id_art = " + idArt + " designation = " + designation +
" prixUnit2 = " + prixUnit2 + " Qté = " + qteStock);
}
} else {
throw Exception("Failed to load Data");
}
}
Future<List<ListArtMemeCate>> _getSameArticleData(int id_article, String nom_article) async {
final response = await http.get(BASE + "xxxxxxx?id_art="+ id_article.toString() +"&nom_art="+ nom_article);
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
TheDetailData myData = new TheDetailData.fromJson(jsonResponse);
List<ListArtMemeCate> datas = [];
for (var i = 0; i < myData.articledetail.list_art_meme_cate .length; i++) {
datas.add(myData.articledetail.list_art_meme_cate[i]);
}
return datas;
} else {
throw Exception("Failed to load Data");
}
}
#override
Widget build(BuildContext context) {
int localStockQte = int.parse(qteStock);
double localPrixUnit2 = double.parse(prixUnit2.toString());
Widget article_afficher333 = FutureBuilder(
future: _getSameArticleData(widget.id_art, widget.art_desgnation),
builder: (context, snapshot) {
//if(snapshot.data != null){
if (snapshot.hasData) {
List<ListArtMemeCate> articledata = snapshot.data;
return new Container(
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
childAspectRatio: 0.7,
padding: EdgeInsets.only(top: 8, left: 6, right: 6, bottom: 12),
children: List.generate(articledata.length, (index){
return Container(
child: Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailArticlePage(int.parse(articledata[index].idArt) , articledata[index].designation)));
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: (MediaQuery.of(context).size.width / 2 - 40),
width: double.infinity,
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl: BASEIMAGES+articledata[index].lienPhoto,
placeholder: (context, url) => Center(
child: CircularProgressIndicator()
),
errorWidget: (context, url, error) => new Icon(Icons.image),
),
),
Padding(
padding: const EdgeInsets.only(top: 2.0),
child: ListTile(
title: Text((() {
if(articledata[index].designation.length >12){
return "${articledata[index].designation.substring(0, 12)}...";}
return "${articledata[index].designation}";
})(), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0, fontFamily: "Questrial")),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 2.0, bottom: 1),
child: Text(articledata[index].prixUnit2+" F CFA", style: TextStyle(
color: Theme.of(context).accentColor,
fontWeight: FontWeight.w700,
fontFamily: 'Questrial'
)),
),
],
),
],
),
),
)
],
),
),
),
);
}),
),
);
} else if (snapshot.hasError) {
return Container(
child: Center(
child: Text(
"Erreur de chargement. Verifier votre connexion internet"),
),
);
}
return new Center(
child: CircularProgressIndicator(),
);
},
);
setState(() {
_panier.nom_article = designation;
_panier.prixUnit2 = double.parse(prixUnit2);
_panier.image_article = lienPhoto;
_panier.prixTot = qtecompter*double.parse(prixUnit2);
_panier.quantite = qtecompter ;
_panier.id_article = int.parse(idArt);
});
void _incrementeQte(){
setState((){
if(qtecompter >= localStockQte){
qtecompter = localStockQte;
}
qtecompter++;
});
}
void _decrementeQte(){
setState((){
if(qtecompter <=1){
qtecompter = 1;
}else{
qtecompter--;
}
});
}
String _getPrixTotal(){
setState((){
prixTotal = qtecompter*localPrixUnit2;
aAfficher = prixTotal.toString();
});
return aAfficher;
}
void _ajouterPanier() async {
//s.addToCart(widget.article);
var result = await helper.addCart(_panier);
var result3 = await helper.getCount();
/*int result;
result = await helper.addCart(_panier);
if(result != 0)
print('STATUS Panier Save Successfully');*/
}
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("designation", style: TextStyle(color: Colors.white),),
iconTheme: new IconThemeData(color: Colors.white),
actions: <Widget>[
Stack(
children: <Widget>[
IconButton(
icon: Icon(Icons.shopping_cart, color: Colors.white, ),
onPressed: () {
//showAlertDialog(context);
Navigator.push(context, new MaterialPageRoute(builder: (context) => PanierPage()));
},
),
Container(
width: 25,
height: 25,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(30),
),
alignment: Alignment.center,
child: Text(taillePanier.toString(),
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12
),)
),
],
),
],
),
body: new ListView(
children: <Widget>[
new Container(
height: 240,
child: new Hero(tag: lienPhoto, child: new Material(
child: InkWell(
child: new Image.network(
BASEIMAGES + lienPhoto,
fit: BoxFit.cover),
),
)),
),
new Container(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 10,left: 5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Text(designation.toString(), style: new TextStyle(fontSize: 20.0, color: Colors.black, fontFamily: 'Questrial'),),
],
),
),
SizedBox(height: 10.0),
Padding(
padding: const EdgeInsets.only(left: 280),
child: new Text(prixUnit2.toString()+" F CFA", style: new TextStyle(fontSize: 15.0, color: Colors.black54, fontFamily: 'Questrial', fontWeight: FontWeight.bold),),
),
SizedBox(height: 10.0),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20, bottom: 10),
child: new Text(descrip.toString(), style: new TextStyle(fontSize: 15.0, color: Colors.grey, fontFamily: 'Questrial'),),
),
SizedBox(height: 10.0),
new Container(
height: 100,
child: Column(
children: <Widget>[
Container(
height: 1.0,
color: Colors.grey,
),
Padding(
padding: const EdgeInsets.only(left: 25, right: 25, top: 20),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(AppLocalizations.of(context)
.translate('_QUANTITY'), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15, fontFamily: 'Questrial'),),
Text(AppLocalizations.of(context)
.translate('_TOTAL_PRICE'), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15, fontFamily: 'Questrial'), ),
],
),
),
Padding(
padding: const EdgeInsets.only(left: 10, right: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Row(
children: <Widget>[
new IconButton(
icon: Icon(Icons.remove_circle_outline, color: Colors.amber, ),
onPressed: _decrementeQte,
),
new Text("$qtecompter"),
new IconButton(
icon: Icon(Icons.add_circle_outline, color: Colors.amber, ),
onPressed: _incrementeQte,
),
],
),
new Text(_getPrixTotal()+" F CFA", style: new TextStyle(fontSize: 20.0, color: Colors.grey),),
],
),
),
Container(
height: 1.0,
color: Colors.grey,
),
],
),
),
//articleMemeCategorie()
],
),
),
Padding(
padding: const EdgeInsets.only(top: 10, left: 25, ),
child: Text(AppLocalizations.of(context)
.translate('_ITEMS_OF_SAME_QUATEGORY'), style: TextStyle(fontFamily: 'Questrial', fontSize: 15, fontWeight: FontWeight.bold),),
),
article_afficher333,
],
),
bottomNavigationBar: new Container(
color: Colors.white,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child: new MaterialButton(
onPressed: (){showAlertDialog(context);},
child: new Row(
//crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
IconButton(
//widget.article
icon: Icon(Icons.store, color: Colors.white,),
onPressed: () {
//showAlertDialog(context);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailBoutiquePage(int.parse(idBou)))); },
),
],
),
color: Color(0xFFFFC23A),
),),
Expanded(
flex: 2,
child: new MaterialButton(
onPressed: (){
_ajouterPanier();
},
child: new Container(
child: new Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.add_shopping_cart, color: Colors.white,),
),
Text(AppLocalizations.of(context)
.translate('_ADD_TO_CART'), style: TextStyle(color: Color(0xFFFFFFFF)))
],
),
),
color: Color(0xFFFFC23A),
),),
Expanded(child: new MaterialButton(
onPressed: (){showAlertDialog(context);},
child: new Text(AppLocalizations.of(context)
.translate('_BUY_NOW'), style: TextStyle(color: Color(0xFFFFFFFF)),),
color: Color(0xFFFFC23A),
),),
],
),
)
);
}
}
Without seeing your full detail page and error log it is difficult to tell exactly what your error is.
From the information you have given it sounds like you are trying to retrieve data from an Http request, and then use that information for the display of your page. Have you tried using a FutureBuilder in the detail page? This will allow you to display a page while waiting for the data from the server, and will then display the data from the server once it has been retrieved.

Flutter - 2 required argument(s) expected, but 0 found

I'm creating a double listView app, its going well so far but I've hit a snag that I can't seem to fix.
I'm getting the error[dart] 2 required argument(s) expected, but 0 found.
In my eyes this should be an easy fix, I thought I just needed to change...
body: _cryptoWidget(),
to...
body: _cryptoWidget(currency, color),
This hasn't worked, and I still get the error stated above.
This is the code I'm using to stimulate the error;
import 'package:flutter/material.dart';
import 'background.dart';
import 'package:flutter/foundation.dart';
import 'package:cryptick_nice_ui/data/crypto_data.dart';
import 'package:cryptick_nice_ui/modules/crypto_presenter.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> implements CryptoListViewContract {
CryptoListPresenter _presenter;
List<Crypto> _currencies;
bool _isLoading;
final List<MaterialColor> _colors = [Colors.blue, Colors.indigo, Colors.red];
List<String> items = [
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
"Item 7",
"Item 8"
];
_HomePageState() {
_presenter = new CryptoListPresenter(this);
}
#override
void initState() {
super.initState();
_isLoading = true;
_presenter.loadCurrencies();
}
#override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(
color: const Color(0xFF273A48),
),
child: new Stack(
children: <Widget>[
new Scaffold(
appBar: new AppBar(
title: new Text("cryp"),
elevation: 0.0,
backgroundColor: Colors.transparent,
),
backgroundColor: Colors.transparent,
body: _cryptoWidget(),
)
],
),
);
}
Widget _cryptoWidget(Crypto currency, MaterialColor color) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
final headerList = new ListView.builder(
itemBuilder: (context, index) {
EdgeInsets padding = index == 0?const EdgeInsets.only(
left: 20.0, right: 10.0, top: 4.0, bottom: 30.0):const EdgeInsets.only(
left: 10.0, right: 10.0, top: 4.0, bottom: 30.0);
_getHtmlUI();
return new Padding(
padding: padding,
);
},
scrollDirection: Axis.horizontal,
itemCount: items.length,
);
new Scaffold(
appBar: new AppBar(
title: new Text('hello'),
elevation: 0.0,
backgroundColor: Colors.transparent,
),
backgroundColor: Colors.transparent,
body: new Container(
child: new Stack(
children: <Widget>[
new Padding(
padding: new EdgeInsets.only(top: 10.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Align(
alignment: Alignment.centerLeft,
child: new Padding(
padding: new EdgeInsets.only(left: 8.0),
child: new Text(
'Your Feed',
style: new TextStyle(color: Colors.white70),
)),
),
new Container(
height: 300.0, width: _width, child: headerList),
new Expanded(child:
ListView.builder(
itemBuilder:
(context, index) {
_getCryptoUI(currency, color);
}
)
)
],
),
),
],
),
),
);
return new Container(
decoration: new BoxDecoration(
color: const Color(0xFF273A48),
),
child: new Stack(
children: <Widget>[
new CustomPaint(
size: new Size(_width, _height),
painter: new Background(),
),
],
),
);
}
Container _getHtmlUI() {
return new Container(
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(10.0),
color: Colors.lightGreen,
boxShadow: [
new BoxShadow(
color: Colors.black.withAlpha(70),
offset: const Offset(3.0, 10.0),
blurRadius: 15.0)
],
image: new DecorationImage(
image: new ExactAssetImage(
'assets/img_0.jpg'),
fit: BoxFit.fitHeight,
),
),
// height: 200.0,
width: 200.0,
child: new Stack(
children: <Widget>[
new Align(
alignment: Alignment.bottomCenter,
child: new Container(
decoration: new BoxDecoration(
color: const Color(0xFF273A48),
borderRadius: new BorderRadius.only(
bottomLeft: new Radius.circular(10.0),
bottomRight: new Radius.circular(10.0))),
height: 30.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'hello',
style: new TextStyle(color: Colors.white),
)
],
)),
)
],
),
);
}
ListTile _getCryptoUI(Crypto currency, MaterialColor color) {
return new ListTile(
title: new Column(
children: <Widget>[
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
height: 72.0,
width: 72.0,
decoration: new BoxDecoration(
color: Colors.lightGreen,
boxShadow: [
new BoxShadow(
color:
Colors.black.withAlpha(70),
offset: const Offset(2.0, 2.0),
blurRadius: 2.0)
],
borderRadius: new BorderRadius.all(
new Radius.circular(12.0)),
image: new DecorationImage(
image: new ExactAssetImage(
"cryptoiconsBlack/"+currency.symbol.toLowerCase()+"#2x.png",
),
fit: BoxFit.cover,
)),
),
new SizedBox(
width: 8.0,
),
new Expanded(
child: new Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
new Text(
currency.name,
style: new TextStyle(
fontSize: 14.0,
color: Colors.black87,
fontWeight: FontWeight.bold),
),
_getSubtitleText(currency.price_usd, currency.percent_change_1h),
],
)),
new Icon(
Icons.shopping_cart,
color: const Color(0xFF273A48),
)
],
),
new Divider(),
],
),
);
}
Widget _getSubtitleText(String priceUSD, String percentageChange) {
TextSpan priceTextWidget = new TextSpan(
text: "\$$priceUSD\n", style: new TextStyle(color: Colors.black));
String percentageChangeText = "1 hour: $percentageChange%";
TextSpan percentageChangeTextWidget;
if (double.parse(percentageChange) > 0) {
percentageChangeTextWidget = new TextSpan(
text: percentageChangeText,
style: new TextStyle(color: Colors.green));
} else {
percentageChangeTextWidget = new TextSpan(
text: percentageChangeText, style: new TextStyle(color: Colors.red));
}
return new RichText(
text: new TextSpan(
children: [priceTextWidget, percentageChangeTextWidget]));
}
#override
void onLoadCryptoComplete(List<Crypto> items) {
// TODO: implement onLoadCryptoComplete
setState(() {
_currencies = items;
_isLoading = false;
});
}
#override
void onLoadCryptoError() {
// TODO: implement onLoadCryptoError
}
}
For more information on other files I use in this app, for instance crypto_data.dart, please see this GitHub repo that I'm using to model certain sections of my code.
The reason why you're getting the error [dart] 2 required argument(s) expected, but 0 found. is because no arguments were passed. The another example you've provided: _cryptoWidget(currency, color) - you're trying to pass a List, which doesn't match the required arguments.
As mentioned in the comments, what you can do here is to define the index for the List to fetch the required values: _cryptoWidget(_currencies[index], _colors[index])

Categories

Resources