FLUTTER: How to change background color inside a gridview? - flutter

I use gridview in flutter and I have a problem, the backgroundcolor of the screen is black but when I return a gridview the background color of the cells are white. I want to change the background color of the cells.
I try to move the gridview inside a container and add a Boxdecoration but it doesn't works, can you help me ? There is my code:
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: Center(
child: Column(
children: <Widget>[
conseil(text, lien),
SizedBox(height: 20,),
Text("GAME PIN", style: TextStyle(fontSize: 40),),
Container(
padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
decoration: BoxDecoration(
border: Border.all(width: 2.0, color: Color(0xffa8277b)),
borderRadius: BorderRadius.circular(15),
),
child: Text(id, style: TextStyle(fontSize: 30),)),
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('rooms')
.document(id)
.collection('users')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return Text("Chargement....");
else {
return GridView.count(
crossAxisCount: 6,
children: snapshot.data.documents
.map((DocumentSnapshot document) {
return OvalPic(
document['photo'], document['couleur']);
}).toList());
}
},
),
),
button(mypink, 'COMMENCER', context),
SizedBox(height: 15,)
],
),
),
);
}

Wrapping it in a Container and adding color to it should do it,
return Container(
color: Colors.black,
child: GridView.count(
crossAxisCount: 4,
children: snapshot.data.documents
.map((DocumentSnapshot document) {
return OvalPic(
document['photo'], document['couleur']);
}).toList()));

I was able to remove Grid Tile background color using elevation property. I tried as below,
GridTile(
child: new Card(
elevation: 0,
color: Colors.transparent,
child:Text('Sample')))
Sharing this as it may be useful later.

Related

Flutter: Keyboard causing a renderflex overflow error

I'm trying to display a message to the user unless there is a renderflex overflow error of 212px at the bottom. Actually, I use a separate widget to display the message, and every time I try to type with my phone, I get an error. I tried several solutions but none of them worked for me.
I would appreciate it if someone took a look. Thanks in advance!
Here is my code:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(
'Passation chat',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Messages'),
Container(
height: 590,
child: SingleChildScrollView(
physics: ScrollPhysics(), reverse: true, child: ShowMessages()),
),
Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: Colors.blue, width: 0.2))),
child: TextField(
controller: msgController,
decoration: InputDecoration(hintText: 'Enter Message'),
),
),
),
IconButton(
onPressed: () {
if (msgController.text.isNotEmpty) {
storeMessage.collection('Messages').doc().set({
"msg": msgController.text.trim(),
"user": logInUser!.email.toString(),
"time": DateTime.now()
});
msgController.clear();
FocusManager.instance.primaryFocus?.unfocus();
}
},
icon: Icon(
Icons.send,
color: Colors.blueAccent,
))
],
),
],
),
);
}
}
class ShowMessages extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Messages')
.orderBy('time')
.snapshots(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
QueryDocumentSnapshot x = snapshot.data!.docs[index];
return ListTile(
title: Column(
crossAxisAlignment: logInUser!.email == x['user']
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
Container(
child: Column(children: [
Text(x['msg']),
SizedBox(
height: 5,
),
Text(
x['user'],
style: TextStyle(fontSize: 10),
)
]),
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
decoration: BoxDecoration(
color: logInUser!.email == x['user']
? Colors.blue.withOpacity(0.2)
: Colors.amber.withOpacity(0.1),
borderRadius: BorderRadius.circular(15)),
),
],
),
);
},
shrinkWrap: true,
primary: true,
physics: ScrollPhysics(),
);
},
);
}
}
Screenshots from the app:
Make SingleChildScrollView the first widget of Scaffold body.
Fixed it by wrapping the Column widget by a SingleChildScrollView. Thanks mates!

setState not updating inside ListView

I have tried looking at similar questions here without any luck. I wonder if my problem is due to my ListView being inside a FutureBuilder which again is inside its own widget, which again is inside an alertdialog with its own statefulbuilder.
I am trying to change the color of a button inside a listview after it is pressed.
The color is updated, but I have to rerender the alertdialog/listview to see the changes.
I removed a good portion of irrelevant code to make it readable and more easy to see the structure.
The structure of the code is as follows:
class _MainPageState extends State<MainPage> {
bool test = false; //Bool controlling the color of the button
_showDialog1(chosenTitle, choice) { //Function to trigger dialog
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(builder: (context, setState) { //StatefulBuilder placed because thats what I thought was needed for my project to work.
return AlertDialog(
content: SingleChildScrollView(
child: choice,
),}})})
Widget hamburgerValue(value) { //THIS is the widget placed in the "choice" parameter above
var _messageController = TextEditingController();
List<dynamic> privSessions = [];
return FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Wrap(
children: [
Column(
children: [
Container(
constraints: BoxConstraints(maxWidth: 300),
child: Text('Placeholder'),
),
Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 0, 30.0),
child: Container(
color: Colors.white,
width: 300,
child: TextField(
controller: _messageController,
maxLines: 5,
decoration: InputDecoration(
//labelText: 'Din melding her',
border: OutlineInputBorder(),
hintText: 'Din melding her'),
),
),
),
],
),
SizedBox(
width: 150,
height: 300,
child: Container(
child: ListView.builder(
itemCount: privSessions.length,
itemBuilder: (context, i) {
bool test = false; //VARIABLE TO DETERMINE COLOR CHANGE
if (i == 0) {
return Column(
children: [
Text(privSessions[i]['day'],
style: TextStyle(fontSize: 20)),
Padding(
padding:
const EdgeInsets.only(bottom: 10.0),
child: Text(
datoFull,
style: TextStyle(fontSize: 15),
),
),
ElevatedButton(
onPressed: privSessions[i]
['available']
? () {
setState(() {
test = true; //WHERE THE SETSTATE HAPPENS
});
}
: null,
style: ElevatedButton.styleFrom(
primary: test
? Colors.red
: Colors.cyan),
child: Column(
children: [
Text(time,
style: TextStyle(
color: Colors.white)),
],
))
],
);
}

Flutter - using ListView.builder inside FutureBuilder and SliverList - scroll behaviour

I'm trying to improve my app and want to wrap an existing FutureBuilder with a SliverList. Unfortunately I'm having a strange and incomprehensible scrolling behaviour.
Here's my code so far:
#override
Widget build(BuildContext context) {
return Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 300,
floating: true,
flexibleSpace: FlexibleSpaceBar(
title: Padding(
padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
child: Text(
'some subtext here...',
style: TextStyle(
fontStyle: FontStyle.italic,
color: Colors.white,
fontSize: 12.0)),
),
background: Stack(
fit: StackFit.expand,
children: [
Container(
child: Image.network(
'https://dummyimage.com/600x400/000/fff',
fit: BoxFit.cover,
),
),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment(0.0, 0.5),
end: Alignment(0.0, 0.0),
colors: <Color>[
Color(0xcc000000),
Color(0x55000000),
],
),
),
),
],
),
),
),
SliverPadding(
padding: EdgeInsets.only(top: 10),
sliver: SliverList(
delegate: SliverChildListDelegate([
Container(
child: FutureBuilder(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Text('loading...');
} else {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext content, int index) {
// return Text('Text ' + snapshot.data[index].name);
return snapshot.hasData ? Card(
elevation: 4,
child: ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(snapshot.data[index].image_url),
),
trailing: Text('Test'),
title: Text(snapshot.data[index].name),
subtitle: Text(snapshot.data[index].latin_name, style: TextStyle(
fontStyle: FontStyle.italic,
)),
onTap: () {
/*Navigator.push(context,
new MaterialPageRoute(builder: (context)=> DetailPage(snapshot.data[index]))
);*/
print('tapped');
},
),
) : Text('no Data');
},
);
//return Text('loading complete');
}
}
),
),
],),
),
)
],
)),
],
));
}
The SliverAppBar gets displayed correctly, but unfortunately since adding the Slivers my FutureBuilder doesn't display anything at all.
After adding scrollDirection and shrinkWrap to the ListView the data get's displayed but I'm unable to scroll correctly.
When dragging it at the red area the List snaps back up right after releasing The SliverAppBar doesn't shrink either. When scrolling in the green area the Sliver Header works correctly and the Scrolling doesn't snap right at the top when releasing.
Has anyone had this issue before? Or could someone explain on why this could happen?

streambuilder not displaying data in list

I'm trying to display a list of employees in my app. Here's the code I got so far:
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 20,top: 20),
child: Container(
height: 40,
width: 120,
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.12),
borderRadius: BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsets.all(10),
child: Text("Employees",
style: TextStyle(
fontSize: 22,
color: Colors.black,
fontWeight: FontWeight.w600,
)),
),
),
),
StreamBuilder(
stream: Firestore.instance.collection("Employees").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: Text("Fetching data..."));
} else if(snapshot.connectionState == ConnectionState.done){
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data.documents[index]['name']));
},
);
} else {
return Text("hol up");
}
}),
],
);
When I run the app, it just shows 'Employees' and 'hol up' in a column. Why does the list of employees not show?
I solved the issue by simply adding shrinkWrap: true in my listview.
This should work. Also get the data from the indexed document.
ListTile(
title: Text(snapshot.data.documents[index].data['name']));

Flutter: Creating GridView From Firebase Realtime DB items

Currently, in my app's homescreen I have a firebase_animated_list widget which creates a listView. However, I want to show these items in a GridView because it'll look much better.
Here's my code snippet.👇🏼
body: Column(
children: <Widget>[
Flexible(
child: FirebaseAnimatedList(
query: firebaseRef,
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return InkWell(
child: ListTile(
contentPadding: EdgeInsets.all(7),
title: Text(mynode[index].key),
leading: CircleAvatar(
radius: 30,
child: FittedBox(
child: Text(mynode[index].id),
),
),
trailing: Icon(Icons.play_arrow),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => DemoDb(
id: othernode[index].id,
),
),
),
),
);
},
),
),
],
),
This perfectly creates a list of items but how should I change it to a GridView? I tried using GridView.count in place of ListTile widget. but because it was nested inside the firebase_animated_list , Each grid is layed out inside this animated list.
Is there any plugins or libraries that can help me in this? perhaps a code snippet Or if someone can suggest me any better approach to achieve this, it would mean world to me.
Thank You.
try Using StreamBuilder to load the items in a map and then use a Gridview and then you can populate the Gridview with your data.
have a look at the following Example:
Here we have a model of the data that we're trying to pull from firebase.
class Product {
String key;
String cardid;
String cardname;
String cardimage;
int cardprice;
String carddiscription;
Product(this.key,this.cardid,this.cardname,this.cardimage,this.cardprice,this.carddiscription);
}
and here is how to implement a GridView inside a StreamBuilder and populate it with the data:
return StreamBuilder(
stream: FirebaseDatabase.instance
.reference()
.child("Products")
.onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
products.clear();
map.forEach((dynamic, v) =>
products.add( new Product(v["key"],v["cardid"] , v["cardname"],v["cardimage"] ,v["cardprice"], v["carddiscription"]))
);
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: products.length,
padding: EdgeInsets.all(2.0),
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: (){
},
child: Padding(
padding: EdgeInsets.all(5),
child: Container(
width: (screenWidth(context)/2)-15,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(15.0)),
image: DecorationImage(
image: NetworkImage(products[index].cardimage),
fit: BoxFit.cover,
),
),
child: Padding(
padding: EdgeInsets.all(0),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(15.0)),
gradient: new LinearGradient(
colors: [
Colors.black,
const Color(0x19000000),
],
begin: const FractionalOffset(0.0, 1.0),
end: const FractionalOffset(0.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
products[index].cardname,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500,color: Colors.white),
),
Text('Rs. ${products[index].cardprice}'
,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w200,color: Colors.white),
),
],
),
),
),
), /* add child content here */
),
),
);
},
);
} else {
return CircularProgressIndicator();
}
}),