Widget is taking maximum space in Flutter - flutter

I have some widgets (message bubbles ) inside a StreamBuilder, however this message bubbles are taking the maximum space possible when they should adapt to the size of the text inside.
This is the code of the main screen:
#override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (context, snapshot){
List<Widget> messagesWidgets = [];
if (snapshot.hasData){
final messages = snapshot.data.docs;
for (var message in messages){
final messageText = message.data()['text'];
final messageSender = message.data()['sender'];
final messageWidget = MessageBubble(
text: messageText,
sender: messageSender,
);
messagesWidgets.add(messageWidget);
}
}
return Expanded(
child: ListView(
//padding: EdgeInsets.symmetric(horizontal: 0.0, vertical: 20.0),
children: messagesWidgets,
),
);
},
),
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 6,
child: TextInput(
textAlign: TextAlign.left,
onChanged: (value){
messageText = value;
},
hintText: 'Type a message',
),
),
Expanded(
flex: 1,
child: Button(
child: Icon(Icons.send, color: background,),
function: (){
if(messageText.trim() == '') return;
_firestore.collection('messages').add({
'text': messageText,
'sender': Usr.email,
});
setState(() {
messageText = '';
});
},
tag: 'hey2d2',
),
),
],
),
),
],
),
);
And this is the code of the message bubbles:
#override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
child: Material(
elevation: 10.0,
borderRadius: BorderRadius.circular(30.0),
color: Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'$sender',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: background,
),
),
Text(
'$text',
style: TextStyle(
fontSize: 15.0,
color: background,
),
),
],
),
),
),
),
);
Here there is a screenshot of what I mean:

This happens because the ListView widget automatically forces its children to take up all the available width. You can bypass this behaviour by wrapping the message bubble container with the Align widget. See below:
#override
Widget build(BuildContext context) {
return Align(
// Set the align's alignment to centerLeft.
alignment: Alignment.centerLeft,
child: Container(
...
),
);
}

Related

not able to return elements with nested gridview builder - fluttter

my case is that I am retrieving values images and text for challenges (like products ...etc), the challenges should appear one by one vertically first the image appears then the text appears over the image in the centre so I used stack and padding and I was able to retrieve one challenge information only, now I want to retrieve all challenges vertically using gridview builder, so I have did this :
Widget build(BuildContext context) {
return GridView.builder(
scrollDirection: Axis.vertical,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: _challenges.length),
itemBuilder: (_, index) {
return InkWell(
onTap: () {},
child: Stack(
children: [
Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image(
image:
NetworkImage(_challenges[index]["image-path"][0]),
fit: BoxFit.cover,
height: 150,
width: 350,
opacity: AlwaysStoppedAnimation(.4),
),
),
),
),
Padding(
padding: const EdgeInsets.all(60.0),
child: Center(
child: Text(
"${_challenges[index]["name"]}\n${_challenges[index]["date"]}",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold),
),
),
),
],
),
);
});
every time i hot reload the app i get this error:
'package:flutter/src/rendering/sliver_grid.dart': Failed assertion: line 319 pos 15: 'crossAxisCount != null && crossAxisCount > 0': is not true.
and in just in case this is how i retrieved the data from Firestore:
List _challenges = [];
fetchChallengeData() async {
var _fireStoreInstance = FirebaseFirestore.instance;
QuerySnapshot qn = await _fireStoreInstance.collection("challenges").get();
setState(() {
for (int i = 0; i < qn.docs.length; i++) {
_challenges.add({
"image-path": qn.docs[i]["image-path"],
"name": qn.docs[i]["name"],
"date": qn.docs[i]["date"],
});
}
});
}
#override
void initState() {
fetchChallengeData();
super.initState();
}
the home screen where i use to display the element looks like:
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.purple,
title: Text(
"أتحداك",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: SingleChildScrollView(
child: Column(
children: [
AdsBanner(),
SizedBox(
height: 50,
),
Directionality(
textDirection: TextDirection.rtl,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text(
"التحديات",
style: TextStyle(fontSize: 20),
),
Text(
" (إضغط على التحدي للإشتراك به)",
style: TextStyle(fontSize: 15),
)
],
),
),
),
ChallengeCard(),
],
),
),
endDrawer: NavigationDrawer());
so basically the parent is a column and the parent of the column is singleChildScrollView,
any help I would be grateful, Thanks.
We are getting data from future fetchChallengeData, So it will be null initially, Try returning another widget on null or empty cases
Widget build(BuildContext context) {
return _challenges!=null && _challenges.isNotEmpty? GridView.builder(...): SizedBox.shrink();
Though _challenges.isNotEmpty enough while we've List _challenges = [];
I think we are seeking somthing like this
Widget myGridView() {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4, //number of items on single Row
),
itemCount: _challenges.length, // number of item will render
itemBuilder: (context, index) => Text("Your item Builder"),
);
}
Widget placement
body: Column(
children: [
AdsBanner(),
SizedBox(
height: 50,
),
Directionality(
textDirection: TextDirection.rtl,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text(
"التحديات",
style: TextStyle(fontSize: 20),
),
Text(
" (إضغط على التحدي للإشتراك به)",
style: TextStyle(fontSize: 15),
)
],
),
),
),
Expanded(child: ChallengeCard()),
],
),

Flutter: Errors when wrapping Layoutbuilder and Text in Column

I currently have a listview with an alphabet scroller on the side. I'm trying to add a searchbox to the top, but whenever I wrap something in a column, I get errors.
Using the current code, ListView inside Stack is throwing Vertical viewport was given unbounded height.
When I remove the column and Text('TestString'), my code works fine. I have tried adding an Expandable around the ListView.Builder but this also doesn't seem to solve it.
#override
Widget build(BuildContext context) {
height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: Text(widget.title,
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.bold)),
centerTitle: true,
),
body: Column(
children: [
Text('TestString'),
new LayoutBuilder(
builder: (context, constraints) {
return new Stack(children: [
//Causes the current issue
ListView.builder(
itemCount: exampleList.length,
controller: _controller,
itemExtent: _itemsizeheight,
itemBuilder: (context, position) {
return Padding(
padding: const EdgeInsets.only(right: 32.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
exampleList[position],
style: TextStyle(fontSize: 20.0),
),
),
));
},
),
Positioned(
right: _marginRight,
top: _offsetContainer,
child: _getSpeechBubble()),
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTapDown: (details) {
_onTapDown(details);
},
child: GestureDetector(
onVerticalDragUpdate: _onVerticalDragUpdate,
onVerticalDragStart: _onVerticalDragStart,
onVerticalDragEnd: (details) {
setState(() {
isPressed = false;
});
},
child: Container(
//height: 20.0 * 26,
color: Colors.transparent,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: []..addAll(
new List.generate(_alphabet.length,
(index) => _getAlphabetItem(index)),
),
),
),
),
),
),
]);
},
),
],
),
);
}
_getSpeechBubble() {
return isPressed
? new SpeechBubble(
nipLocation: NipLocation.RIGHT,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
width: 30,
child: Center(
child: Text(
"${_text ?? "${_alphabet.first}"}",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
),
),
),
),
],
),
)
: SizedBox.shrink();
}
ValueGetter? callback(int value) {}
_getAlphabetItem(int index) {
return new Expanded(
child: new Container(
width: 40,
height: 20,
alignment: Alignment.center,
child: new Text(
_alphabet[index],
style: (index == posSelected)
? new TextStyle(fontSize: 16, fontWeight: FontWeight.w700)
: new TextStyle(fontSize: 12, fontWeight: FontWeight.w400),
),
),
);
}
You can wrap your LayoutBuilder() with Expanded() like this and it won't show an error.
return Container(
child: Column(
children: [
Text("Header"),
Expanded(
child: ListView.builder(
itemCount:50,
itemBuilder: (BuildContext context, int index) {
return Text("List Item $index");
},
),
),
Text("Footer"),
],
),
);
You can try the code here

Multiply value of textformfield in Listview and get the sum of it

I have two textformfields in my listview. I want to get the value from each of them, multiply for each index and ultimately get the total value. It's more like an invoice. This will be done onChange of the textformfields. I have the following code which does not return the correct output.
class _OrderBookingState extends State<OrderBooking> {
#override
Widget build(BuildContext context) {
TextEditingController controller = new TextEditingController();
List<TextEditingController> _textFieldRateControllers = new List();
List<TextEditingController> _textFieldQtyControllers = new List();
var productCount = 0;
return Scaffold(
appBar: AppBar(
title: Center(child: Text(widget.shop.shopName)),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: StreamBuilder<List<ProductModel>>(
stream: DatabaseService().productList,
builder: (context,snapshot){
productCount = snapshot.data.length;
if(snapshot.hasData){
return Flexible(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index){
_textFieldQtyControllers.add(new TextEditingController());
_textFieldRateControllers.add(new TextEditingController());
_textFieldRateControllers[index].text = snapshot.data[index].rate;
_textFieldQtyControllers[index].text = "0";
countTotal(){
var totalSum = 0.0;
_textFieldQtyControllers.forEach((element) {
var rateDouble = double.parse(_textFieldRateControllers[index].text);
var qtyDouble = double.parse(_textFieldQtyControllers[index].text);
var multiple = rateDouble*qtyDouble;
totalSum += multiple;
//calculateTotal(element, _textFieldRateControllers[index].text, _textFieldQtyControllers[index].text);
}
);
print("Total is $totalSum" );
}
return Padding(
padding: EdgeInsets.only(top: 8.0),
child: Card(
margin: EdgeInsets.fromLTRB(10.0, 6.0, 10.0, 0.0),
child: ListTile(
leading: CircleAvatar(
radius: 25.0,
backgroundColor: Colors.deepOrangeAccent,
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
width: 175,
child: Text(snapshot.data[index].productName,),
),
// Expanded(child: Container(
// width: 10,
// child: Center(child: Text(snapshot.data[index].productName,)))),
SizedBox(width: 5,),
Expanded(child: Container(
width: 10,
child: TextFormField(
controller: _textFieldRateControllers[index],
textAlign: TextAlign.center,
onChanged: (text){
countTotal();
},
//onChanged: (text){calculateTotal(productCount, _textFieldRateControllers[index].text, _textFieldQtyControllers[index].text);},
),
),
),
SizedBox(width: 5,),
Expanded(child: TextFormField(
controller: _textFieldQtyControllers[index],
textAlign: TextAlign.center,
onChanged: (text){
countTotal();
//calculateTotal(productCount, _textFieldRateControllers[index].text, _textFieldQtyControllers[index].text);
},
)
)
],
),
subtitle: Text('MRP ' + snapshot.data[index].mrp),
),
),
);
}
),
);
}else{
return Loading();
}
}
),
),
Container(
margin: EdgeInsets.fromLTRB(10.0, 6.0, 10.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Total Value: 0/-",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold,backgroundColor: Colors.greenAccent)
),
RaisedButton(
child: Text("Save",style: TextStyle(fontSize: 18.0),),
color: Colors.green,
textColor: Colors.white,
highlightColor: Colors.lightGreenAccent,
onPressed: (){
//print(_textFieldQtyControllers[1].text);
},
)
],
),
)
],
),
);
}
}
As per the image it should return (260+85+67 = 412) which I'm not getting.Please let me know how to achieve this.
The reason is you are assigning qty as zero in itembuilder of your listview:-
_textFieldQtyControllers[index].text = "0";
So replace it with 10 as per your image:-
_textFieldQtyControllers[index].text = "10";

Why does this row don't wrap in flutter

What the problem is I have to render some texts which are in a row and also it should wrap when it doesn't have enough space but the row does not wrap.
I have used wrapping it Expanded, Wrap, and tried some stackoverflow answers but none of them work
Below is my code for it
Widget xyz(List _list) {
return Padding(
padding: const EdgeInsets.fromLTRB(50, 10, 40, 10),
child: InkWell(
onTap: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
'Title : ',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
),
Wrap(children: [
Row(children: [
for (int i = 0; i < _list.length; i++)
Container(
padding: const EdgeInsets.only(right: 8),
child: Text(
'${_list[i]}',
style: TextStyle(fontSize: 13),
),
),
]),
]),
],
),
),
);
}
class _Page3State extends State<Page3> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
xyz([
'Text1',
'Text2',
'Text3',
'Text4',
'Text5',
'Text6',
'Text7',
]),
//other widgets
],
),
);
}
}
And this is the output I am getting
I want the 'Text6' & 'Text7' Text widgets to go on the next line.
This is a working example:
The issues are incorrect Flexible (Expanded) placing, and your Wrap had a Row child instead of directly placed children.
Widget xyz(List _list) {
return Padding(
padding: const EdgeInsets.fromLTRB(50, 10, 40, 10),
child: InkWell(
onTap: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
'Title : ',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
),
Flexible(
child: Wrap(
children: [
for (int i = 0; i < _list.length; i++)
Container(
padding: const EdgeInsets.only(right: 8),
child: Text(
'${_list[i]}',
style: TextStyle(fontSize: 13),
),
),
],
),
),
],
),
),
);
}
class _Page3State extends State<Page3> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
xyz([
'Text1',
'Text2',
'Text3',
'Text4',
'Text5',
'Text6',
'Text7',
]),
//other widgets
],
),
);
}
}

Flutter: How to merge two StreamBuilder and show the output in a card

I'm kinda stuck with what I'm trying to do. I'm trying to merge my two Stream Builder to show the output as one in a card. In my first StreamBuilder thats where I'm getting some infos of the user like the info that he posted, what they need like that. And in my 2nd StreamBuilder thats where I get his/her name, contacts like that. Is it possible to merge it as one? so I'll get the data as one also.
This is how I use my StreamBuilders.
1st stream:
StreamBuilder<QuerySnapshot>(
stream: db.collection('HELP REQUEST').where('Type_OfDisaster', isEqualTo: '[Drought]').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: snapshot.data.documents
.map((doc) => buildItem(doc))
.toList()
);
} else {
return Container(
child: Center(
child: CircularProgressIndicator()
)
);
}
}
);
2nd Stream:
StreamBuilder<QuerySnapshot>(
stream: db.collection('USERS').where('User_ID', isEqualTo: widget.Uid).snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: snapshot.data.documents
.map((doc) => buildItem(doc))
.toList()
);
} else {
return Container(
child: Center(
child: CircularProgressIndicator()
)
);
}
}
);
Here is where I output the data I get in the stream builder:
Container buildItem(DocumentSnapshot doc) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
return Container(
child: Card(
elevation: 5,
child: Padding(
padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
CircleAvatar(
radius: 30,
backgroundColor: Colors.black,
),
SizedBox(
width: 10,
),
Text('Name: '),
Text(
'${doc.data['Name_ofUser']}',
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.w500),
)
],
),
],
),
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20,
),
Row(
children: <Widget>[
Text('Date:'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${doc.data['Help_DatePosted']}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.w500),
),
),
],
),
Row(
children: <Widget>[
Text('Location:'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${doc.data['Help_Location']}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w500),
),
),
],
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text('Description:'),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${doc.data['Help_Description']}',
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w500),
),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Container(
height: _height * 0.05,
width: _width * 0.20,
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(20.0))),
color: Color(0xFF121A21),
onPressed: () {
_viewingRequest(doc.data);
},
child: Text(
'View',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w800),
),
),
),
)
],
),
],
),
),
),
);
}
Is it possible to do it? Please help me.
You can listen to the snapshots without using a StreamBuilder directly, like this:
List<HelpRequestsPlusUsers> helpRequestsPlusUsers = [];
List<User> allUsers = [];
List<HelpRequest> helpRequests = [];
#override
void initState() {
db.collection('USERS').where('User_ID', isEqualTo: widget.Uid).snapshots().listen((snapshot){
allusers = snapshot.data.documents;
mergeUsersWithHelpRequests();
});
db.collection('HELP REQUEST').where('Type_OfDisaster', isEqualTo: '[Drought]').snapshots().listen((snapshot){
helpRequests = snapshot.data.documents;
mergeUsersWithHelpRequests();
});
super.initState();
}
void mergeUsersWithHelpRequests(){
// Run the code to merge your allUsers and helpRequests data into a helpRequestsPlusUsers List
}
Widget
Widget _buildHelpRequestsPlusUsersWidget (){
if (helpRequestsPlusUsers.isNotEmpty) {
return ListView.builder(
itemBuilder: (context, index){
return buildItem(helpRequestsPlusUsers[index]);
}
);
} else {
return Container(
child: Center(
child: CircularProgressIndicator()
)
);
}
}