Related
I have container where I display total amount of all orders done by customer of today, this week and this month. How can I get this data and display from firebase.
Here is my code where I have Total Sales, and in Orders I have recieved, delivered, In process.
How can I get this data by matching the dateTime. Please do help me.
When I try my method I get Class '_JsonQuerySnapshot' has no instance method '[]' this error
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('merchant')
.doc(appdata.uid)
.collection('orders')
.where('dateTime', isEqualTo: DateTime.now())
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print('####################');
print(snapshot.data);
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 20.w),
child: Row(
children: [
Text('₹ ${snapshot.data[0]['price']}\t ',
style: TextStyle(
fontFamily: 'lato',
color: textColorPrimary,
fontSize: 16.sp,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
)),
Text('(${appdata.sizeoforders})',
style: TextStyle(
fontFamily: 'lato',
color: textColorPrimary,
fontSize: 9.sp,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
)),
],
),
);
}
return CircularProgressIndicator();
}),
Divider(
thickness: 1,
color: fromCssColor("rgba(0, 0, 0, 0.1)"),
),
SizedBox(
height: 10.h,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.w),
child: Row(
children: [
Text('Orders',
style: TextStyle(
fontFamily: 'lato',
color: textColorSecondary,
fontSize: 16.sp,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
)),
],
),
),
SizedBox(
height: 10.h,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.w),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'28\nReceived',
style: TextStyle(
fontFamily: 'lato',
color: textColorPrimary,
fontSize: 11.sp,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
),
textAlign: TextAlign.center,
),
Text(
'20\nDelivered',
style: TextStyle(
fontFamily: 'lato',
color: textColorPrimary,
fontSize: 11.sp,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
),
textAlign: TextAlign.center,
),
Text(
'4\nIn Process',
style: TextStyle(
fontFamily: 'lato',
color: textColorPrimary,
fontSize: 11.sp,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
),
textAlign: TextAlign.center,
),
],
),
),
So I am creating a chat-app. I need to show the list of all users in the firebase by mentioning their user-name and email.
I am getting the above stated error on line 56.
Also if I remove the null check operator in the line
QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
And replace late at the beginning it will produce late initialization error.
import 'package:chatapp/services/database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class Search extends StatefulWidget {
_Search createState() => _Search();
}
class _Search extends State<Search> {
QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
bool isLoading = false;
bool haveUserSearched = false;
DatabaseMethods databaseMethods = new DatabaseMethods();
var searchEditingController = TextEditingController();
InitiateSearch() async {
if (searchEditingController.text.isNotEmpty) {
setState(() {
isLoading = true;
});
await databaseMethods.GetUserByUsername(searchEditingController.text)
.then((snapshot) {
searchResultSnapshot = snapshot;
print("$searchResultSnapshot");
setState(() {
isLoading = false;
haveUserSearched = true;
});
});
}
}
Widget UserList() {
return Container(
height: 500,
child: ListView.builder(
itemCount: searchResultSnapshot?.docs.length,
itemBuilder: (context, index) {
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"],
searchResultSnapshot?.docs[index].data()["userEmail"],
);
}),
);
}
Widget UserTile(String? userName, String? userEmail) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
userName!, //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail!,
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
),
Spacer(),
GestureDetector(
onTap: () {
null;
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(24)),
child: Text(
"Message",
style: TextStyle(color: Colors.white, fontSize: 16),
),
),
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onPressed: () {
Navigator.pop(context);
});
},
),
title: Text('Search'),
),
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: [
Container(
height: 36,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Colors.black,
),
BoxShadow(
color: Colors.black,
spreadRadius: -12.0,
blurRadius: 12.0,
),
],
),
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 0, horizontal: 10.0),
child: TextFormField(
style: TextStyle(color: Colors.black),
controller: searchEditingController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Search',
hintStyle: TextStyle(color: Colors.grey),
icon: GestureDetector(
onTap: () {
InitiateSearch();
},
child: Icon(
Icons.search,
color: Colors.grey,
),
),
suffixIcon: IconButton(
onPressed: searchEditingController.clear,
icon: Icon(
Icons.cancel_rounded,
color: Colors.grey,
),
),
),
),
),
), //Search
SizedBox(
height: 12,
),
UserList(),
],
),
));
}
}
Here is my Database file.
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseMethods {
GetUserByUsername(String username) async {
return await
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["userName"]);
});
});
}
Future<void> UploadUserInfo(userData) async {
FirebaseFirestore.instance.collection("users").add(userData).catchError((e) {
print(e.toString());
});
}
}
I would really appritiate your help on this.
You can replace below piece of code
children: [
Text(
userName!, //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail!,
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
with
children: [
Text(
userName ?? "", //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail ?? "",
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
In place of
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"],
searchResultSnapshot?.docs[index].data()["userEmail"],
);
use this
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"]??"",
searchResultSnapshot?.docs[index].data()["userEmail"]??"",
);
And replace the String? with String in (Remove ?)
Widget UserTile(String userName, String userEmail)
and use the value like the following
Text(userName,style: TextStyle(color: Colors.white, fontSize: 16),),
How do I retrieve a specific URL from the real-time database?
final database = FirebaseDatabase(
databaseURL:
"https://trackkit-a5cf3-default-rtdb.asia-southeast1.firebasedatabase.app")
.reference()
.child('NTU')
.child(widget.referenceName);
.
.
.
Widget _buildItem(String imgPath, String labName, int quantity, String expiry,
Function onAdd, Function onSubtract, Function onDelete) {
void _minusNum() {
onSubtract();
}
void _onAdd() {
onAdd();
}
void _onDelete() {
onDelete();
}
return Padding(
padding: const EdgeInsets.only(left: 0.0, right: 10, top: 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
GestureDetector(
onLongPress: _onDelete,
child: Row(children: [
Hero(
tag: imgPath,
child: const Image(
image: NetworkImage(''), <---THIS IS THE LINE
fit: BoxFit.cover,
height: 120.0,
width: 130.0)),
const SizedBox(width: 10.0),
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
labName,
style: const TextStyle(
fontFamily: 'Montserrat',
fontSize: 12.0,
fontWeight: FontWeight.bold,
),
),
Text(
expiry,
style: const TextStyle(
fontFamily: 'Montserrat',
fontSize: 12.0,
fontWeight: FontWeight.bold,
),
),
Container(
width: 100.0,
height: 30.0,
margin: const EdgeInsets.only(left: 0.0, top: 5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(17.0),
color: const Color(0xFF7A9BEE)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
onTap: _minusNum,
child: Container(
height: 25.0,
width: 25.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(7.0),
color: const Color(0xFF7A9BEE)),
child: const Center(
child: Icon(
Icons.remove,
color: Colors.white,
size: 20.0,
),
),
),
),
Text(quantity.toString(),
style: const TextStyle(
color: Colors.white,
fontFamily: 'Montserrat',
fontSize: 15.0)),
InkWell(
onTap: _onAdd,
child: Container(
height: 25.0,
width: 25.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(7.0),
color: Colors.white),
child: const Center(
child: Icon(
Icons.add,
color: Color(0xFF7A9BEE),
size: 20.0,
),
),
),
),
],
),
)
]),
]),
),
],
));
}
.
.
.
tag: imgPath,
child: const Image(
image: NetworkImage(''),
fit: BoxFit.cover,
height: 120.0,
width: 130.0)
I am able to retrieve the rest of the item in the firebase, but I am unable to retrieve the Image.
The error appears:
======== Exception caught by image resource service ================================================
The following ArgumentError was thrown resolving an image codec:
Invalid argument(s): No host specified in URI file:///lists%5Bindex%5D%5B%22Image%22%5D
The question is not really clear, but This error is definitely happening because you're assigning an invalid image link '' to your NetworkImage.
How can i get rid of this strange white background? I want to use weather widget in my app and i want it to be above MyGridView with buttons. I tried to do it with expanded but im always getting white background and my widget. I would like to use my weather widget as normal widget (like others) and be able to apply padding in home_screen.dart etc.
home_screen.dart
Widget build(BuildContext context) {
Color _iconColor = Colors.white.withOpacity(0.1);
double Size = MediaQuery.of(context).size.width;
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Color(0xff362a19),
Color(0xff101011),
Color(0xff301119)
])),
child: Scaffold(
appBar: CustomAppBar(),
backgroundColor: Colors.transparent,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
//IDEALNE https://github.com/Matt-rempel/flutter-weather-app/tree/master/assets/icons
Padding(
padding: EdgeInsets.only(top: 10, left: 25),
child: Text(
'${greeting()}',
style: TextStyle(
fontFamily: 'Helvetica Bold',
fontSize: 32,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 10, left: 25),
child: Text(
'Zarządzaj swoimi urządzeniami',
style: TextStyle(
fontFamily: 'Helvetica Bold',
fontSize: 16,
color: Colors.grey,
fontWeight: FontWeight.w600),
),
),
Padding(
padding: EdgeInsets.only(top: 20, left: 25),
),
Expanded(
child: CurrentWeatherPage(locations, context), //<--------------------------- HERE
),
Expanded(
child: MyGridView(),
),
],
//
),
bottomNavigationBar: Container(
padding: const EdgeInsets.only(bottom: 18.0),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
bottomLeft: Radius.circular(30.0),
bottomRight: Radius.circular(30.0),
),
child: BottomAppBar(
elevation: 0,
color: Colors.transparent,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
icon: Icon(
Icons.home,
color: _iconColor,
size: 28,
),
onPressed: null),
IconButton(
icon: Icon(
Icons.tv,
color: _iconColor,
size: 28,
),
onPressed: () {
setState(() {
_iconColor = Color(0xffc5073f);
});
}),
//
IconButton(
icon: Icon(
Icons.notifications,
color: _iconColor,
size: 28,
),
onPressed: null),
IconButton(
icon: Icon(
Icons.settings,
color: _iconColor,
size: 28,
),
onPressed: null),
],
),
),
),
//
) //
),
);
}
current_weather.dart
import 'package:firebaseauthproject/models/location.dart';
import 'package:firebaseauthproject/models/weather.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'extensions.dart';
class CurrentWeatherPage extends StatefulWidget {
final List<Location> locations;
final BuildContext context;
const CurrentWeatherPage(this.locations, this.context);
#override
_CurrentWeatherPageState createState() =>
_CurrentWeatherPageState(this.locations, this.context);
}
class _CurrentWeatherPageState extends State<CurrentWeatherPage> {
final List<Location> locations;
final Location location;
final BuildContext context;
_CurrentWeatherPageState(List<Location> locations, BuildContext context)
: this.locations = locations,
this.context = context,
this.location = locations[0];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
currentWeatherViews(this.locations, this.location, this.context)
],
),
);
}
}
Widget currentWeatherViews(
List<Location> locations, Location location, BuildContext context) {
Weather _weather;
return FutureBuilder(
builder: (context, snapshot) {
if (snapshot.hasData) {
_weather = snapshot.data;
if (_weather == null) {
return Text("Error getting weather");
} else {
return Column(children: [
weatherBox(_weather),
]);
}
} else {
return Center(child: CircularProgressIndicator());
}
},
future: getCurrentWeather(location),
);
}
Widget weatherBox(Weather _weather) {
return Stack(children: [
Container(
padding: const EdgeInsets.all(15.0),
margin: const EdgeInsets.all(15.0),
height: 160.0,
decoration: BoxDecoration(
color: Colors.indigoAccent,
borderRadius: BorderRadius.all(Radius.circular(20))),
),
ClipPath(
clipper: Clipper(),
child: Container(
padding: const EdgeInsets.all(15.0),
margin: const EdgeInsets.all(15.0),
height: 160.0,
decoration: BoxDecoration(
color: Colors.indigoAccent[400],
borderRadius: BorderRadius.all(Radius.circular(20))))),
Container(
padding: const EdgeInsets.all(15.0),
margin: const EdgeInsets.all(15.0),
height: 160.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20))),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
getWeatherIcon(_weather.icon),
Container(
margin: const EdgeInsets.all(5.0),
child: Text(
"${_weather.description.capitalizeFirstOfEach}",
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 16,
color: Colors.white),
)),
Container(
margin: const EdgeInsets.all(5.0),
child: Text(
"H:${_weather.high.toInt()}° L:${_weather.low.toInt()}°",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
color: Colors.white),
)),
])),
Column(children: <Widget>[
Container(
child: Text(
"${_weather.temp.toInt()}°",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 60,
color: Colors.white),
)),
Container(
margin: const EdgeInsets.all(0),
child: Text(
"Feels like ${_weather.feelsLike.toInt()}°",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
color: Colors.white),
)),
])
],
),
)
]);
}
Image getWeatherIcon(String _icon) {
String path = 'assets/weather/';
String imageExtension = ".png";
return Image.asset(
path + _icon + imageExtension,
width: 70,
height: 70,
);
}
class Clipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
Path path = Path();
path.moveTo(0, size.height - 20);
path.quadraticBezierTo((size.width / 6) * 1, (size.height / 2) + 15,
(size.width / 3) * 1, size.height - 30);
path.quadraticBezierTo((size.width / 2) * 1, (size.height + 0),
(size.width / 3) * 2, (size.height / 4) * 3);
path.quadraticBezierTo((size.width / 6) * 5, (size.height / 2) - 20,
size.width, size.height - 60);
path.lineTo(size.width, size.height - 60);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
path.close();
return path;
}
#override
bool shouldReclip(Clipper oldClipper) => false;
}
Future getCurrentWeather(Location location) async {
Weather weather;
String city = location.city;
String apiKey = "0e97f1773e9ed9e93d3f99a91d14344f";
var url =
"https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric";
final response = await http.get(url);
if (response.statusCode == 200) {
weather = Weather.fromJson(jsonDecode(response.body));
}
return weather;
}
If you put two Expanded widgets in a Column, it will try to take equal amount space. If you want to get rid of that white space change your code from this...
Expanded(
child: CurrentWeatherPage(locations, context),
),
Expanded(
child: MyGridView(),
),
to this....
Flexible(
fit: FlexFit.tight,
child: CurrentWeatherPage(locations, context),
),
Expanded(
child: MyGridView(),
),
or if you want the two widgets share equal space in column change your code from this..
body: Column(
children: <Widget>[
currentWeatherViews(this.locations, this.location, this.context)
],
),
To this..
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
currentWeatherViews(this.locations, this.location, this.context)
],
),
My CSS:
background: linear-gradient(91.97deg, #F8A170 14.73%, #FFCD61 97.52%);
border-radius: 10px;
I want to go with flutter but when I give these colors to the container widget with child elevated button, I can't get the result I want. I made the button style transparent, but still I couldn't solve it.
Based on your image and css, You can simply decorate the style of ElevatedButton.
DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
gradient: const LinearGradient(
colors: [
Color(0xFFF8A170),
Color(0xFFFFCD61),
],
),
),
child: SizedBox(
width: 400,
height: 75,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 0,
primary: Colors.white.withOpacity(0),
padding: const EdgeInsets.all(0),
),
onPressed: () {},
child: const Text(
"Search a room",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
),
),
),
More about
DecoratedBox and ElevatedButton
Please refer to below example code
Using Elevated Button
LinearGradient yellowLinearGradientValues() {
return LinearGradient(
colors: [Colors.orange, Color(0xffFFB800).withOpacity(0.65)],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
elevation: 0.0,
padding: EdgeInsets.zero,
primary: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
side: BorderSide(
width: 0.0,
color: Colors.orange,
style: BorderStyle.none,
),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
gradient: yellowLinearGradientValues(),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 8.0,
),
child: Text(
"Search a Room" ?? "",
textAlign: TextAlign.start,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 24.0,
),
),
),
),
),
),
);
}
LinearGradient yellowLinearGradientValues() {
return LinearGradient(
colors: [Colors.orange, Color(0xffFFB800).withOpacity(0.7)],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.transparent),
elevation: MaterialStateProperty.all(0.0),
padding: MaterialStateProperty.all(EdgeInsets.zero),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
gradient: yellowLinearGradientValues(),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 8.0,
),
child: Text(
"Search a Room" ?? "",
textAlign: TextAlign.start,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 24.0,
),
),
),
),
),
),
);
}