Trouble pulling data from firestore - firebase

database structure screenshotI am building a profile screen and am trying to pull each user's name from a database in firestore using streambuilder. However, my code does not seem to be pulling from the firestore database and I am still getting the same name (each time I run the code) that I had previously hard coded. Below is my code (there are no errors in the actual code). How can I modify my code so that it will actually read from the firestore database?
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:ui' as ui;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Profile Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Profile'),
);
}
}
class ProfileWidget extends StatelessWidget {
final String userId;
ProfileWidget(this.userId);
#override
Widget build(BuildContext context) {
return StreamBuilder<DocumentSnapshot>(
stream:
Firestore.instance.collection('users').document(userId).snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
debugPrint('the snapshot name is:'+ snapshot.data['name']);
User user = User.fromSnapshot(snapshot.data);
return Row(
children: <Widget>[Text(snapshot.data['name'].toString())]);
} else {
return CircularProgressIndicator();
}
});
}
}
class User {
final int name;
final DocumentReference reference;
User.fromMap(Map<String, dynamic> map, {this.reference}) : name = map['name'];
User.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
final String imgUrl =
'https://pixel.nymag.com/imgs/daily/selectall/2017/12/26/26-eric-schmidt.w700.h700.jpg';
return new Stack(
children: <Widget>[
new Container(
color: Colors.blue,
),
new Image.network(
imgUrl,
fit: BoxFit.fill,
),
new BackdropFilter(
filter: new ui.ImageFilter.blur(
sigmaX: 6.0,
sigmaY: 6.0,
),
child: new Container(
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.9),
borderRadius: BorderRadius.all(Radius.circular(50.0)),
),
)),
new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
centerTitle: false,
elevation: 0.0,
backgroundColor: Colors.transparent,
),
drawer: new Drawer(
child: new Container(),
),
backgroundColor: Colors.transparent,
body: new Center(
child: new Column(
children: <Widget>[
new SizedBox(
height: _height / 12,
),
new CircleAvatar(
radius: _width < _height ? _width / 4 : _height / 4,
backgroundImage: NetworkImage(imgUrl),
),
new SizedBox(
height: _height / 25.0,
),
new Text(
'Eric Schmidt',
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: _width / 15,
color: Colors.white),
),
new Padding(
padding: new EdgeInsets.only(
top: _height / 30, left: _width / 8, right: _width / 8),
child: new Text(
'Snowboarder, Superhero and writer.\nSometime I work at google as Executive Chairman ',
style: new TextStyle(
fontWeight: FontWeight.normal,
fontSize: _width / 25,
color: Colors.white),
textAlign: TextAlign.center,
),
),
new Divider(
height: _height / 30,
color: Colors.white,
),
new Row(
children: <Widget>[
rowCell(343, 'POSTS'),
rowCell(673826, 'FOLLOWERS'),
rowCell(275, 'FOLLOWING'),
],
),
new Divider(height: _height / 30, color: Colors.white),
new Padding(
padding: new EdgeInsets.only(
left: _width / 8, right: _width / 8),
child: new FlatButton(
onPressed: () {},
child: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Icon(Icons.person),
new SizedBox(
width: _width / 30,
),
new Text('FOLLOW')
],
)),
color: Colors.blue[50],
),
),
],
),
))
],
);
}
Widget rowCell(int count, String type) => new Expanded(
child: new Column(
children: <Widget>[
new Text(
'$count',
style: new TextStyle(color: Colors.white),
),
new Text(type,
style: new TextStyle(
color: Colors.white, fontWeight: FontWeight.normal))
],
));
}

Related

How to get email of user from firebase in Text Widget

I want to write the User's email under the User's name in the Navigation drawer, but I cannot access the email in Text Widget
I used this code for fetching user email id from Firebase but unable to write inside Text
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
firebase_auth.FirebaseAuth firebaseAuth = firebase_auth.FirebaseAuth.instance;
Future<void> signOut() async {
await firebaseAuth.signOut();
}
dynamic user;
String userEmail;
getCurrentUserInfo() async {
user = await firebaseAuth.currentUser;
userEmail = user.email;
print(userEmail);
return userEmail;
}
static var chartdisplay;
bool isSwitched = true;
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: Builder(
builder: (context) => IconButton(
icon: Image.asset(
"assets/images/menu.png",
),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
backgroundColor: const Color(0xffe8e5af),
elevation: 0,
centerTitle: false,
titleSpacing: 0,
),
drawer: new Drawer(
child: new ListView(
padding: EdgeInsets.zero,
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(vertical: 50, horizontal: 30),
color: const Color(0xffe8e5af),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
CircleAvatar(
radius: 46,
backgroundColor: Colors.white,
child: CircleAvatar(
backgroundImage: AssetImage('assets/images/avatar.jpg'),
radius: 40,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Nabia Salman',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
fontWeight: FontWeight.w700,
),
textAlign: TextAlign.left,
),
Text(
//"${user.email}",
"nabia.salman99#gmail.com",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 9,
color: const Color(0xff000000),
),
textAlign: TextAlign.left,
),
],
),
],
),
),
This is how my screen looks like
Please help me out in finding the solution for this as I am new to Flutter
Thank you in advance

How to get pedometer(stepcountvalue) data on Autoupdate basis from firestore

I want to retrieve StepCountValue from firestore and display it to my app on realtimeAutoupdate basis. RealtimeAutoupdate basis means i want a realtime/without refreshing method.So, if a user cover some distance then he/she gets his/her total walking steps in app.
How to retrieve data from database and throw it in a container(page.dart)
How to get pedometer(stepcountvalue) automatic changing data on Autoupdate and retrieve
With firestore
How to update this data to firestore automatically
This is my main.dart
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_testing/models/brew.dart';
import 'package:flutter_testing/models/user.dart';
import 'package:flutter_testing/screens/Pages/page.dart';
import 'package:flutter_testing/screens/wrapper.dart';
import 'package:flutter_testing/services/auth.dart';
import 'package:flutter_testing/services/database.dart';
import 'dart:async';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:pedometer/pedometer.dart';
import 'package:provider/provider.dart';
void main() => runApp(new NewApp());
class NewApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamProvider<User>.value(
value: AuthService().user,
child: MaterialApp(
home: Wrapper(),
),
);
}
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final AuthService _auth = AuthService();
String muestrePasos = "";
String _km = "Unknown";
String _calories = "Unknown";
String stepCountValue = 'Unknown';
String _showcoin = '0';
StreamSubscription<int> _subscription;
double _numerox; //numero pasos
double _convert;
double _kmx;
double burnedx;
double _coin;
double _porciento;
// double percent=0.1;
#override
void initState() {
super.initState();
//initPlatformState();
setUpPedometer();
}
//inicia codigo pedometer
void setUpPedometer() {
Pedometer pedometer = new Pedometer();
_subscription = pedometer.stepCountStream.listen(_onData,
onError: _onError, onDone: _onDone, cancelOnError: true);
}
void _onData(int stepCountValue1) async {
// print(stepCountValue); //impresion numero pasos por consola
setState(() {
stepCountValue = "$stepCountValue1";
// print(stepCountValue);
});
var dist = stepCountValue1; //pasamos el entero a una variable llamada dist
double y = (dist + .0); //lo convertimos a double una forma de varias
setState(() {
_numerox = y; //lo pasamos a un estado para ser capturado ya convertido a double
});
var long3 = (_numerox);
long3 = num.parse(y.toStringAsFixed(2));
var long4 = (long3 / 10000);
int decimals = 1;
int fac = pow(10, decimals);
double d = long4;
d = (d * fac).round() / fac;
print("d: $d");
getDistanceRun(_numerox);
setState(() {
_convert = d;
print(_convert);
});
}
void reset() {
setState(() {
int stepCountValue1 = 0;
stepCountValue1 = 0;
stepCountValue = "$stepCountValue1";
});
}
void _onDone() {}
void _onError(error) {
print("Flutter Pedometer Error: $error");
}
//function to determine the distance run in kilometers using number of steps
void getDistanceRun(double _numerox) {
var distance = ((_numerox * 76) / 100000);
distance = num.parse(distance.toStringAsFixed(2)); //dos decimales
var distancekmx = distance * 34;
distancekmx = num.parse(distancekmx.toStringAsFixed(2));
//print(distance.runtimeType);
var coiny = ((_numerox * 125) / 100000);
coiny = num.parse(coiny.toStringAsFixed(2));
setState(() {
_km = "$distance";
//print(_km);
});
setState(() {
_kmx = num.parse(distancekmx.toStringAsFixed(2));
});
setState(() {
_coin = num.parse(coiny.toStringAsFixed(2));
//print(_coiny);
});
}
//function to determine the calories burned in kilometers using number of steps
void getBurnedRun() {
setState(() {
var calories = _kmx; //dos decimales
_calories = "$calories";
//print(_calories);
});
}
void coins() {
setState(() {
var showcoin = _coin;
_showcoin = "$showcoin";
});
}
//fin codigo pedometer
#override
Widget build(BuildContext context) {
//print(_stepCountValue);
getBurnedRun();
coins();
return StreamProvider<QuerySnapshot>.value(
value: DatabaseService().step,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: new AppBar(
title: const Text('Step Counter'),
backgroundColor: Colors.black54,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.person),
label: Text('logout'),
onPressed: () async {
await _auth.signOut();
}
),
FlatButton.icon(
icon: Icon(Icons.arrow_back),
label: Text('New Page'),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => pages()));
}
),
],
),
body: new ListView(
padding: EdgeInsets.all(5.0),
children: <Widget>[
Container(
padding: EdgeInsets.only(top: 10.0),
width: 250,
//ancho
height: 250,
//largo tambien por numero height: 300
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment
.bottomCenter, //cambia la iluminacion del degradado
end: Alignment.topCenter,
colors: [Color(0xFFA9F5F2), Color(0xFF01DFD7)],
),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(27.0),
bottomRight: Radius.circular(27.0),
topLeft: Radius.circular(27.0),
topRight: Radius.circular(27.0),
)),
child: new CircularPercentIndicator(
radius: 200.0,
lineWidth: 13.0,
animation: true,
center: Container(
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 50,
width: 50,
padding: EdgeInsets.only(left: 20.0),
child: Icon(
FontAwesomeIcons.walking,
size: 30.0,
color: Colors.white,
),
),
Container(
//color: Colors.orange,
child: Text(
'$stepCountValue',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.purpleAccent),
),
// height: 50.0,
// width: 50.0,
),
],
),
),
percent: 0.217,
//percent: _convert,
footer: new Text(
"Steps: $stepCountValue",
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12.0,
color: Colors.purple),
),
circularStrokeCap: CircularStrokeCap.round,
progressColor: Colors.purpleAccent,
),
),
Divider(
height: 5.0,
),
Container(
width: 80,
height: 100,
padding: EdgeInsets.only(left: 25.0, top: 10.0, bottom: 10.0),
color: Colors.transparent,
child: Row(
children: <Widget>[
new Container(
child: new Card(
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/distance.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
child: Text(
"$_km Km",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 14.0),
),
),
color: Colors.white54,
),
),
VerticalDivider(
width: 20.0,
),
new Container(
child: new Card(
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/burned.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
),
color: Colors.transparent,
),
),
VerticalDivider(
width: 20.0,
),
new Container(
child: new Card(
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/step.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
),
color: Colors.transparent,
),
),
],
),
),
Divider(
height: 2,
),
Container(
padding: EdgeInsets.only(top: 2.0),
width: 150,
//ancho
height: 30,
//largo tambien por numero height: 300
color: Colors.transparent,
child: Row(
children: <Widget>[
new Container(
padding: EdgeInsets.only(left: 40.0),
child: new Card(
child: Container(
child: Text(
"$_km Km",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.white),
),
),
color: Colors.purple,
),
),
VerticalDivider(
width: 20.0,
),
new Container(
padding: EdgeInsets.only(left: 10.0),
child: new Card(
child: Container(
child: Text(
"$_calories kCal",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.white),
),
),
color: Colors.red,
),
),
VerticalDivider(
width: 5.0,
),
new Container(
padding: EdgeInsets.only(left: 10.0),
child: new Card(
child: Container(
child: Text(
"$_showcoin Coins",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.white),
),
),
color: Colors.black,
),
),
],
),
),
],
),
),
),
);
}
}
this is my wrapper.dart
import 'package:flutter_testing/models/user.dart';
import 'package:flutter_testing/screens/authenticate/authenticate.dart';
import 'package:flutter/material.dart';
import 'package:flutter_testing/main.dart';
import 'package:provider/provider.dart';
class Wrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
// return either the Home or Authenticate widget
if (user == null){
return Authenticate();
} else {
return MyApp();
}
}
}
this is page.dart
import 'package:flutter/material.dart';
import 'package:flutter_testing/main.dart';
class pages extends StatefulWidget {
#override
_pagesState createState() => _pagesState();
}
class _pagesState extends State<pages> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.amber,
appBar: new AppBar(
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.arrow_back_ios),
label: Text('back'), onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => MyApp())
);
}
),
],
),
body: Container(),
);
}
}
this is database.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_testing/models/brew.dart';
class DatabaseService {
final String uid;
DatabaseService({ this.uid });
// collection reference
final CollectionReference brewCollection = Firestore.instance.collection('step');
Future<void> updateUserData(int stepCountValue, int _calories, int _km , int _showcoin) async {
return await brewCollection.document(uid).setData({
'stepCountValue': stepCountValue,
'_calories': _calories,
'_km': _km,
'_showcoin': _showcoin,
});
// get brews stream
Stream<QuerySnapshot> get step {
return brewCollection.snapshots();
}
}
this is brew.dart
class Brew {
final int stepCountValue;
Brew({ this.stepCountValue });
}
I hope this is enough to solve my problem. I'm very new to Flutter and I dont know much about firebase and firestore, so it would be nice, if you can say where EXACTLY I have to change WHAT or add WHAT. Thank you so much!!!
You can write a query in the _onData() function of your main.dart file this will update the data automatically whenever there will be any change in your steps. And you can retrieve data in real time using streamBuilder easily.
for example:
void _onData(int stepCountValue1) async {
// print(stepCountValue); //impresion numero pasos por consola
setState(() {
stepCountValue = "$stepCountValue1";
});
final CollectionReference brewCollection = Firestore.instance.collection('step');
await brewCollection.document(uid).setData({
'stepCountValue': stepCountValue,
});
}

Error when pulling data from firestore using streambuilder

I am trying to pull data from my firestore database using flutter but am getting the below error:
type 'String' is not a subtype of type 'ImageProvider'
I am using stream builder and have defined the class but it does not seem to be recognising the image that I need to pull. Below is all the code I have used for my stream builder.
firestore database
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:ui' as ui;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Profile Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Profile'),
);
}
}
class Photo {
final int photourl;
final DocumentReference reference;
Photo.fromMap(Map<String, dynamic> map, {this.reference})
: photourl = map['photourl'];
Photo.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
return StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('users')
.document('testuser')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Stack(
children: <Widget>[
new Container(
color: Colors.blue,
),
new Image.network(
snapshot.data['photourl'].toString(),
fit: BoxFit.fill,
),
new BackdropFilter(
filter: new ui.ImageFilter.blur(
sigmaX: 6.0,
sigmaY: 6.0,
),
child: new Container(
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.9),
borderRadius: BorderRadius.all(Radius.circular(50.0)),
),
)),
new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
centerTitle: false,
elevation: 0.0,
backgroundColor: Colors.transparent,
),
drawer: new Drawer(
child: new Container(),
),
backgroundColor: Colors.transparent,
body: new Center(
child: new Column(
children: <Widget>[
new SizedBox(
height: _height / 12,
),
new CircleAvatar(
radius: _width < _height ? _width / 4 : _height / 4,
backgroundImage: snapshot.data['photourl'],
),
new SizedBox(
height: _height / 25.0,
),
new Text(
snapshot.data['name'],
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: _width / 15,
color: Colors.white),
),
new Padding(
padding: new EdgeInsets.only(
top: _height / 30,
left: _width / 8,
right: _width / 8),
),
new Divider(
height: _height / 15,
color: Colors.white,
),
new Row(
children: <Widget>[
rowCell(
snapshot.data['totalquestions'], 'Answers'),
rowCell('£ 673826', 'Earned'),
],
),
new Divider(
height: _height / 15, color: Colors.white),
],
),
))
],
);
} else {
return CircularProgressIndicator();
}
});
}
Inside your Column widget, you have included a CircleAvatar and passed in a wrong parameter to the backgroundImage property. backgroundImage takes an ImageProvider rather than a String of the photo url.
you should change this:
CircleAvatar(
radius: _width < _height ? _width / 4 : _height / 4,
backgroundImage: snapshot.data['photourl'],
),
to this:
CircleAvatar(
radius: _width < _height ? _width / 4 : _height / 4,
backgroundImage: NetworkImage(snapshot.data['photourl']),
),

How to get array data back to mobile screen from firebase (Flutter)

How to get back array data to the mobile screen.
The String in the firebase is retrieved easily but I have problem with array data.
1) main.dart :
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'firestoreservice.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'taskscreen.dart';
import 'task.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ToDo APP',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Color(0xff543B7A),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Task> items;
FirestoreService fireServ = new FirestoreService();
StreamSubscription<QuerySnapshot> todoTasks;
#override
void initState() {
super.initState();
items=new List();
todoTasks?.cancel();
todoTasks=fireServ.getTaskList().listen((QuerySnapshot snapshot){
final List<Task> tasks=snapshot.documents
.map((documentSnapshot) => Task. fromMap(documentSnapshot.data))
.toList();
setState(() {
this.items = tasks;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: <Widget>[
_myAppBar(context),
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height - 80,
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Stack(children: <Widget>[
// The containers in the background
Column(children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 8.0, right: 8.0),
child: Container(
width: MediaQuery.of(context).size.width,
height: 80.0,
child: Padding(
padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Material(
color: Colors.white,
elevation: 14.0,
shadowColor: Color(0x802196F3),
child: Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'${items[index].name}',
style: TextStyle(
color: Colors.black,
fontSize: 20.0),
),
Text(
'${items[index].size}',
style: TextStyle(
color: Colors.black,
fontSize: 20.0),
),
Container(
child: Image.network(
'${items[index].imageU}',
)),
],
),
),
),
),
),
),
),
]),
]);
}),
),
],
),
);
}
Widget todoType(String icontype) {
IconData iconval;
Color colorval;
switch (icontype) {
case 'travel':
iconval = FontAwesomeIcons.mapMarkerAlt;
colorval = Color(0xff4158ba);
break;
case 'shopping':
iconval = FontAwesomeIcons.shoppingCart;
colorval = Color(0xfffb537f);
break;
case 'gym':
iconval = FontAwesomeIcons.dumbbell;
colorval = Color(0xff4caf50);
break;
case 'party':
iconval = FontAwesomeIcons.glassCheers;
colorval = Color(0xff9962d0);
break;
default:
iconval = FontAwesomeIcons.tasks;
colorval = Color(0xff0dc8f5);
//
}
return CircleAvatar(
backgroundColor: colorval,
child: Icon(iconval, color: Colors.white, size: 20.0),
);
}
Widget _myAppBar(context) {
return Container(
height: 80.0,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFFFA7397),
const Color(0xFFFDDE42),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 5,
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'ToDo Tasks',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
),
),
),
Expanded(
flex: 1,
child: Container(
child: IconButton(
icon: Icon(
FontAwesomeIcons.search,
color: Colors.white,
),
onPressed: () {
//
}),
),
),
],
)),
),
);
}
}
2) task.dart
class Task{
String _name;
String _size;
Task(this._name ,this._size);
Task.map(dynamic obj){
this._name = obj['name'];
this._size=obj['size'];
List<String> imageU= new List<String>();
}
String get name=> _name;
String get size=>_size;
Task.fromMap(Map<String,dynamic> map){
this._name = map['name'];
this._size= map['size'];
this.imageU= List.from(map['images']);
}
}
3) firestoreservice.dart
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'task.dart';
final CollectionReference myCollection =
Firestore.instance.collection('products');
class FirestoreService {
Future<Task> createTODOTask(String name, String size) async {
final TransactionHandler createTransaction = (Transaction tx) async {
final DocumentSnapshot ds = await tx.get(myCollection.document());
};
return Firestore.instance.runTransaction(createTransaction).then((mapData) {
return Task.fromMap(mapData);
}).catchError((error) {
print('error: $error');
return null;
});
}
Stream<QuerySnapshot> getTaskList({int offset, int limit}) {
Stream<QuerySnapshot> snapshots = myCollection.snapshots();
if (offset != null) {
snapshots = snapshots.skip(offset);
}
if (limit != null) {
snapshots = snapshots.take(limit);
}
return snapshots;
}
}
How to get back array data to the mobile screen. The String in the firebase is retrieved easily but I have a problem with array data.
Convert task.dart to see what solution will work:
class Task{
String name;
List<String> size= new List<String>();
Task.fromMap(Map<String,dynamic> map){
this.name = map['name'];
this.size= List.from(map['size' ]);
}
}
And make sure all the documents in the image have "size" field.

error:- Another exception was thrown: A RenderFlex overflowed by 33 pixels on the bottom

[enter image description here]
1Error showing when i run my app...My code is below ...can anyone tell what is wrong with my code
///////////////////////
Error showing when i run my app...My code is below ...can anyone tell what is wrong with my code
///////////////////////
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
import
'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
class OfferPage extends StatefulWidget {
#override
_OfferPageState createState() => new _OfferPageState();
}
class _OfferPageState extends State<OfferPage> {
StreamSubscription<QuerySnapshot> subscription;
List<DocumentSnapshot> offerpostList;
final CollectionReference collectionReference =
Firestore.instance.collection("todos");
#override
void initState() {
// TODO: implement initState
super.initState();
subscription = collectionReference.snapshots().listen((datasnapshot) {
setState(() {
offerpostList = datasnapshot.documents;
});
});
// _currentScreen();
}
#override
void dispose() {
subscription?.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: offerpostList != null? new StaggeredGridView.countBuilder(
padding: const EdgeInsets.all(8.0),
crossAxisCount: 4,
itemCount: offerpostList.length,
itemBuilder: (context, i) {
String imgPath = offerpostList[i].data['url'];
String title = offerpostList[i].data['productTitle'];
return new Material(
elevation: 8.0,
borderRadius:
new BorderRadius.all(new Radius.circular(8.0)),
child: new InkWell(
child:new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(title,style: new TextStyle(
fontStyle: FontStyle.italic,
color: Colors.green[900],
fontSize: 16.0)),
new Hero(
tag: imgPath,
child:
new FadeInImage(
image: new NetworkImage(imgPath),
fit: BoxFit.cover,
placeholder: new AssetImage("assets/logo.png"),
),
),
],
),
),
);
},
staggeredTileBuilder: (i) =>
new StaggeredTile.count(2, i.isEven ? 2 : 3),
mainAxisSpacing: 8.0,
crossAxisSpacing: 8.0,
)
: new Center(
child: new CircularProgressIndicator(),
));
}
}
Column in flutter doesn't have scrolling ability. The issue is your data from firebase cannot be fit inside a single screen. That's why overflow error was thrown. Use ListView instead of Column which has the scrolling ability.
Column widget for available room in the device to get qll data in firebase and also to get scroll effect you can use FirebaseAnimatedList.
For an Olx like gridview with text over image, here is a sample. Try it out and change your question because it might be misleading.
main.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firestore_grid_view/product.dart';
import 'package:firestore_grid_view/product_details.dart';
import 'package:flutter/material.dart';
void main() => runApp(new MaterialApp(
home: new MyApp(),
debugShowCheckedModeBanner: false,
));
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Product> _products = [];
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),
),
body: new StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('products').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new GridView.count(
crossAxisCount: 2,
children: _buildGrid(snapshot.data.documents),
);
},
),
);
}
List<Widget> _buildGrid(List<DocumentSnapshot> documents) {
List<Widget> _gridItems = [];
_products.clear();
for (DocumentSnapshot document in documents) {
_products.add(new Product(
name: document['productTitle'],
category: document['category'],
imageUrl: document['url'],
contactNumber: document['contactNumber']));
}
for (Product product in _products) {
_gridItems.add(_buildGridItem(product));
}
return _gridItems;
}
Widget _buildGridItem(Product product) {
return new GestureDetector(
child: new Card(
child: new Stack(
alignment: Alignment.center,
children: <Widget>[
new Hero(
tag: product.name,
child: new Image.network(product.imageUrl, fit: BoxFit.cover),
),
new Align(
child: new Container(
padding: const EdgeInsets.all(10.0),
child: new Text(product.name,
style: new TextStyle(color: Colors.white)),
color: Colors.black.withOpacity(0.4),
width: double.infinity,
),
alignment: Alignment.bottomCenter,
),
],
),
),
onTap: () => onProductTapped(product),
);
}
onProductTapped(Product product) {
Navigator.of(context).push(new MaterialPageRoute(
builder: (context) => new ProductDetails(product)));
}
}
product_details.dart
import 'package:firestore_grid_view/product.dart';
import 'package:flutter/material.dart';
class ProductDetails extends StatelessWidget {
final Product product;
ProductDetails(this.product);
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Column(
children: <Widget>[
new Expanded(child: new Container()),
new Hero(
tag: product.name,
child: new Image(
image: new NetworkImage(product.imageUrl),
fit: BoxFit.fill,
width: double.infinity,
height: 300.0,
)),
new Padding(
padding: const EdgeInsets.all(15.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Padding(
padding: const EdgeInsets.only(right: 8.0),
child: new Text(
'Category -',
style: new TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
),
),
new Text(
product.category,
style: new TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
),
],
),
),
new Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Padding(
padding: const EdgeInsets.only(right: 8.0),
child: new Text(
'Contact Number -',
style: new TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
),
),
new Text(
product.contactNumber,
style: new TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
),
],
),
),
new Expanded(child: new Container()),
],
),
);
}
}
product.dart
class Product {
final name, category, imageUrl, contactNumber;
Product({this.name, this.category, this.imageUrl, this.contactNumber});
}

Resources