How can I apply the data I received from Firebase first? - firebase

Given the following code :
Widget Topstocklist(Size size) {
firestore
.collection('stock')
.orderBy("dailynewscount", descending: true)
.limit(1)
.get()
.then((QuerySnapshot qs)
{
qs.docs.forEach((doc){
name = (doc['name']);
perc = (doc['perc']);
price = (doc['price']);
newscount = (doc['dailynewscount']);
print("100");
});
}
);
return Container(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
'',
style: TextStyle(
color: Color.fromRGBO(0, 0, 0, 0.7),
fontFamily: 'Content',
fontSize: size.width * 0.025,
fontWeight: FontWeight.normal,
height: 1,
),
) // Firebase 적용 사항
,
Container(
child: Column(
children: [
Topstock(size, "deci", "+3.2%", 75000, 1200),
Topstock(size, name, perc, price ,newscount),
],
))
]));
}
Widget Topstock(Size size, String stockname, var stockperc, var stockprice, var newscount) {
print(stockperc);
}
Key point code :
print("100")
print(stockperc).
Expected
I/flutter (15287): 100
I/flutter (15287): //perc = (doc['perc']);
I/flutter (15287): +3.2%
output
I/flutter (15287): +3.2%
I/flutter (15287):
I/flutter (15287): 100
I think this problem relates to the task processing, i.e., asynchronous work, before importing data from the Firebase, but I have not found a solution
How can I get the data from the Firebase and then run the Topstock code?

Related

type '_AssertionError' is not a subtype of type 'String'

I've been dealing with this problem for a long time. I am trying to parse a set of items underloved items for each user (Uid). I am getting the response body and it is been converted to list.But I am getting this error:
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building FutureBuilder<dynamic>(dirty, state: _FutureBuilderState<dynamic>#7125a):
type '_AssertionError' is not a subtype of type 'String'
The relevant error-causing widget was:
FutureBuilder<dynamic> file:///C:/Users/arunb/AndroidStudioProjects/resplash/lib/pages/bookmark.dart:35:15
When the exception was thrown, this was the stack:
#0 BookmarkPage.build.<anonymous closure> (package:resplash/pages/bookmark.dart:47:44)
#1 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:775:55)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
...
Codes :
bookmark.dart
class BookmarkPage extends StatelessWidget {
const BookmarkPage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
final sb = context.watch<SignInBloc>();
return RefreshIndicator(
onRefresh: () async {
await context.read<BookmarkBloc>().getData();
},
child: Scaffold(
backgroundColor: Theme.of(context).primaryColor,
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
centerTitle: false,
title: Text('Saved Items'),
),
body: sb.guestUser == true
? EmptyPage(
icon: FontAwesomeIcons.heart,
title: 'No wallpapers found.\n Sign in to access this feature',
)
: FutureBuilder(
future: context.watch<BookmarkBloc>().getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if (snapshot.data.length == 0)
return EmptyPage(
icon: FontAwesomeIcons.heart,
title: 'No wallpapers found',
);
return _buildList(snapshot);
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error),
);
}
return Center(
child: CupertinoActivityIndicator(),
);
},
),
),
);
}
Widget _buildList(snapshot) {
return StaggeredGridView.countBuilder(
crossAxisCount: 4,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
List d = snapshot.data;
return InkWell(
child: Stack(
children: <Widget>[
Hero(
tag: 'bookmark$index',
child: cachedImage(d[index]['image url'])),
Positioned(
bottom: 15,
left: 12,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
d[index]['category'],
style: TextStyle(color: Colors.white, fontSize: 18),
)
],
),
),
Positioned(
right: 10,
top: 20,
child: Row(
children: [
Icon(Icons.favorite,
color: Colors.white.withOpacity(0.5), size: 25),
Text(
d[index]['loves'].toString(),
style: TextStyle(
color: Colors.white.withOpacity(0.7),
fontSize: 16,
fontWeight: FontWeight.w600),
),
],
),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsPage(
tag: 'bookmark$index',
imageUrl: d[index]['image url'],
catagory: d[index]['category'],
timestamp: d[index]['timestamp'],
)));
},
);
},
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 4 : 3),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
padding: EdgeInsets.all(15),
);
}
}
getData() method
final FirebaseFirestore firestore = FirebaseFirestore.instance;
getData() async {
SharedPreferences sp = await SharedPreferences.getInstance();
String _uid = sp.getString('uid');
final DocumentReference ref = firestore.collection('users').doc(_uid);
DocumentSnapshot snap = await ref.get();
List d = snap['loved items'];
List filteredData = [];
if (d.isNotEmpty) {
await firestore
.collection('contents')
.where('timestamp', whereIn: d)
.get()
.then((QuerySnapshot snap) {
filteredData = snap.docs;
});
}
notifyListeners();
return filteredData;
}
How can I solve this problem? I don't exactly know what is the reason and how to solve this problem.
Can't say for sure just based on this info, but my best guess is that
firestore
.collection('contents')
.where('timestamp', whereIn: d)
.get()
is returning an error.
But I would advise to take full advantage of await since you are using it. Also add a catch on the get() method. So do something like:
if (d.isNotEmpty) {
try {
const snapshot:QuerySnapshot = await firestore
.collection('contents')
.where('timestamp', whereIn: d)
.get();
(*)
fiteredData = snapshot.docs
}
catch(e) {
console.log(e)
// or/and error handling
}
}
(*) you can also try to log the snapshot at the asterix position in the code ((*)) to try to track down the error (if you think there is any chance that the assign is causing problems)
I am not sure if this fix your issue (without a reproducible example is pretty hard to know exactly what is going wrong) but it should at the very least help you to track down the problem.

Unhandled Exception: type 'int' is not a subtype of type 'String' Error in flutter

Im really new to the flutter and stuck at this point im designing the uber clone but not able to get the searched place details and also the polyline is not coming only the progress bar its get stuck over there only loading loading.....
E/flutter (20208): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'int' is not a subtype of type 'String'
E/flutter (20208): #0 HelperMethods.getDirectionDetails (package:cab_rider/helpers/helpermethods.dart:85:22)
E/flutter (20208): <asynchronous suspension>
E/flutter (20208): #1 _MainPageState.getDirection (package:cab_rider/mainpage.dart:349:23)
E/flutter (20208): <asynchronous suspension>
E/flutter (20208): #2 _MainPageState.build.<anonymous closure> (package:cab_rider/mainpage.dart:243:29)
E/flutter (20208): <asynchronous suspension>
E/flutter (20208):
This is my HelperMethods.dart file code :
import 'package:cab_rider/datamodels/address.dart';
import 'package:cab_rider/datamodels/directiondetails.dart';
import 'package:cab_rider/dataprovider/appdata.dart';
import 'package:cab_rider/globalvariable.dart';
import 'package:cab_rider/helpers/requesthelper.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
class HelperMethods{
static Future<String> findCordinateAddress(Position position, context) async {
String placeAddress = '';
String st1, st2, st3, st4;
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult != ConnectivityResult.mobile && connectivityResult != ConnectivityResult.wifi) {
return placeAddress;
}
String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng= ${position.latitude}, ${position.longitude}&key=$mapKey';
var response = await RequestHelper.getRequest(url);
if(response != 'failed'){
placeAddress = response['results'][0]['formatted_address'];
var placeId;
var longitude;
var latitude;
var placeFormattedAddress;
var placeName;
st1 = placeAddress = response["results"][0]["address_components"][0]["long_name"];
st2 = placeAddress = response["results"][0]["address_components"][1]["long_name"];
st3 = placeAddress = response["results"][0]["address_components"][2]["long_name"];
st4 = placeAddress = response["results"][0]["address_components"][3]["long_name"];
placeAddress = st1 + ", " + st2 + ", " + st3 + ", " + st4;
Address pickupAddress = new Address(placeId: placeId , longitude: longitude, latitude: latitude, placeFormattedAddress: placeFormattedAddress, placeName: placeName);
pickupAddress.longitude = position.longitude;
pickupAddress.latitude = position.latitude;
pickupAddress.placeName = placeAddress;
Provider.of<AppData>(context, listen: false).updatePickupAddress(pickupAddress);
}
return placeAddress;
}
static Future<DirectionDetails?> getDirectionDetails(LatLng startPosition, LatLng endPosition) async {
String url = 'https://maps.googleapis.com/maps/api/directions/json?origin=${startPosition.latitude},${startPosition.longitude}&destination=${endPosition.latitude},${endPosition.longitude}&mode=driving&key=$mapKey';
var response = await RequestHelper.getRequest(url); //errorline
if(response == 'failed'){
return null;
}
var durationText;
var durationValue;
var distanceText;
var distanceValue;
var encodedPoints;
DirectionDetails directionDetails = DirectionDetails(distanceText: distanceText, distanceValue: distanceValue, durationText: durationText, durationValue: durationValue, encodedPoints: encodedPoints);
directionDetails.durationText = response['routes'][0]['legs'][0]['duration']['text'];
directionDetails.durationValue = response['routes'][0]['legs'][0]['duration']['value']; //error line
directionDetails.distanceText = response['routes'][0]['legs'][0]['distance']['text'];
directionDetails.distanceValue = response['routes'][0]['legs'][0]['distance']['value'];
directionDetails.encodedPoints = response['routes'][0]['overview_polyline']['points'] ;
return directionDetails;
}
}
This is my MainPage.dart file code: -
import 'package:cab_rider/brand_colors.dart';
import 'package:cab_rider/dataprovider/appdata.dart';
import 'package:cab_rider/helpers/helpermethods.dart';
import 'package:cab_rider/searchpage.dart';
import 'package:cab_rider/styles/styles.dart';
import 'package:cab_rider/widgets/BrandDivider.dart';
import 'package:cab_rider/widgets/ProgressDialog.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:async';
import 'package:outline_material_icons/outline_material_icons.dart';
import 'dart:io';
import 'package:provider/provider.dart';
class MainPage extends StatefulWidget {
static const String id ='mainpage';
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
double searchSheetHeight = (Platform.isIOS) ? 300 : 275 ;
Completer<GoogleMapController> _controller = Completer();
late GoogleMapController mapController;
double mapBottomPadding = 0;
var geoLocator = Geolocator();
Position? currentPosition;
void setupPositionLocator() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.bestForNavigation);
currentPosition = position;
LatLng pos = LatLng(position.latitude, position.longitude);
CameraPosition cp = new CameraPosition(target: pos, zoom: 14);
mapController.animateCamera(CameraUpdate.newCameraPosition(cp));
String address = await HelperMethods.findCordinateAddress(position, context);
print(address);
}
static final CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
drawer: Container(
width: 250,
color: Colors.white,
child: Drawer(
child: ListView(
padding: EdgeInsets.all(0),
children: <Widget>[
Container(
color: Colors.white,
height: 160,
child: DrawerHeader(
decoration: BoxDecoration(
color: Colors.white,
),
child: Row(
children: <Widget>[
Image.asset('images/user_icon.png', height: 60, width: 60,),
SizedBox(width: 15,),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Shubham',style: TextStyle(fontSize: 20, fontFamily: 'Brand-Bold'),),
SizedBox(height: 5,),
Text('View Profile'),
],
)
],
),
),
),
BrandDivider(),
SizedBox(height: 10,),
ListTile(
leading: Icon(OMIcons.cardGiftcard),
title: Text('Free Rides', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.creditCard),
title: Text('Payments', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.history),
title: Text('Ride History', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.contactSupport),
title: Text('Support', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.info),
title: Text('About', style: kDrawerItemStyle,),
)
],
),
),
),
body:Stack(
children: <Widget>[
GoogleMap(
padding: EdgeInsets.only(bottom: mapBottomPadding),
mapType: MapType.normal,
myLocationButtonEnabled: true,
initialCameraPosition: _kGooglePlex,
myLocationEnabled: true,
zoomGesturesEnabled: true,
zoomControlsEnabled: true,
onMapCreated: (GoogleMapController controller){
_controller.complete(controller);
mapController = controller;
setState(() {
mapBottomPadding = (Platform.isAndroid) ? 280 : 270 ;
});
setupPositionLocator();
},
),
/// MenuButton
Positioned(
top: 44,
left: 20,
child: GestureDetector(
onTap: (){
scaffoldKey.currentState!.openDrawer();
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 5.0,
spreadRadius: 0.5,
offset: Offset(
0.7,
0.7,
),
)
]
),
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: Icon(Icons.menu, color: Colors.black87,),
),
),
),
),
/// SearchSheet
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
height: searchSheetHeight,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topLeft: Radius.circular(15), topRight: Radius.circular(15)),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 15.0,
spreadRadius: 0.5,
offset: Offset(
0.7,
0.7,
)
)
]
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 5,),
Text('Nice to see you!', style: TextStyle(fontSize: 10),),
Text('Where are you going?', style: TextStyle(fontSize: 18, fontFamily: 'Brand-Bold'),),
SizedBox(height: 20,),
GestureDetector(
onTap: () async {
var response = await Navigator.push(context, MaterialPageRoute(
builder: (context) => SearchPage()
));
if(response == 'getDirection'){
await getDirection(); // error line
}
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(4),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 5.0,
spreadRadius: 0.5,
offset: Offset(
0.7,
0.7,
)
)
]
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: <Widget>[
Icon(Icons.search, color: Colors.blueAccent,),
SizedBox(width: 10,),
Text('Search Destination'),
],
),
),
),
),
SizedBox(height: 22,),
Row(
children: <Widget>[
Icon(OMIcons.home, color: BrandColors.colorDimText,),
SizedBox(width: 12,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Add Home'),
SizedBox(height: 3,),
Text('Your residental address ',
style: TextStyle(fontSize: 11, color: BrandColors.colorDimText,),
),
]
)
],
),
SizedBox(height: 10,),
BrandDivider(),
SizedBox(height: 16,),
Row(
children: <Widget>[
Icon(OMIcons.workOutline, color: BrandColors.colorDimText,),
SizedBox(width: 12,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Add Work'),
SizedBox(height: 3,),
Text('Your Office address ',
style: TextStyle(fontSize: 11, color: BrandColors.colorDimText,),
),
]
)
],
),
],
),
),
),
)
],
)
);
}
Future<void> getDirection() async {
var pickup = Provider.of<AppData>(context, listen: false).pickupAddress;
var destination = Provider.of<AppData>(context, listen: false).destinationAddress;
var pickLatLng = LatLng(pickup!.latitude, pickup.longitude);
var destinationLatLng = LatLng(destination!.latitude, destination.longitude);
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => ProgressDialog(status: 'Please wait',)
);
var thisDetails = await HelperMethods.getDirectionDetails(pickLatLng, destinationLatLng);
Navigator.pop(context);
print(thisDetails!.encodedPoints);
}
}
This is my RequestHelper.dart file :
import 'dart:convert';
import 'package:http/http.dart' as http;
class RequestHelper{
static Future<dynamic> getRequest(String url) async {
http.Response response = await http.get(Uri.parse(url));
try {
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
return decodedData;
} else {
return 'failed';
}
} catch (e) {
return 'failed';
}
}
}
#1 error points out at this line
directionDetails.durationText = response['routes'][0]['legs'][0]['duration']['text'];
directionDetails.durationValue = response['routes'][0]['legs'][0]['duration']['value']; //error line
directionDetails.distanceText = response['routes'][0]['legs'][0]['distance']['text'];
directionDetails.distanceValue = response['routes'][0]['legs'][0]['distance']['value'];
directionDetails.encodedPoints = response['routes'][0]['overview_polyline']['points'] ;
#2 error points out this line
var response = await RequestHelper.getRequest(url);
#3 error points out this line
await getDirection();
Please help me to solve this error its my final year project...
Instead of
String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng= ${position.latitude}, ${position.longitude}&key=$mapKey';
use
String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng= ${position.latitude.toString()}, ${position.longitude.toString()}&key=$mapKey';
and
Instead of
String url = 'https://maps.googleapis.com/maps/api/directions/json?origin=${startPosition.latitude},${startPosition.longitude}&destination=${endPosition.latitude},${endPosition.longitude}&mode=driving&key=$mapKey';
use
String url = 'https://maps.googleapis.com/maps/api/directions/json?origin=${startPosition.latitude},${startPosition.longitude}&destination=${endPosition.latitude.toString()},${endPosition.longitude.toString()}&mode=driving&key=$mapKey';
You have to convert longitude and latitude to String values using toString() method before concatenating!
using google_directions_api saved me while dealing with direction
Unhandled Exception: type 'int' is not a subtype of type 'String'
It seems you declare a Variable as an Int on the server-side make that Variable as String the problem will be resolve.

Unhandled Exception: [cloud_firestore/not-found] Some requested document was not found

In my flutter application, this is the error thats coming,
The issue that im facing is after i click on the address line (shown in the following image)
issue picture
we enter a map screen, which is the following image issue img in order to set the delivery location,
but then after i press "continue" the following error pops up,
W/Firestore(21269): (23.0.3) [WriteStream]: (23ef168) Stream closed with status: Status{code=NOT_FOUND, description=No document to update: projects/grocery-app-d1d06/databases/(default)/documents/users/ZwfXvwLAKP0g7Kbnb1k2, cause=null}.
E/flutter (21269): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: [cloud_firestore/not-found] Some requested document was not found.
E/flutter (21269): #0 MethodChannelDocumentReference.update (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:60:7)
E/flutter (21269): <asynchronous suspension>
E/flutter (21269): #1 UserServices.updateUserData (package:groceryapp/services/user_services.dart:16:5)
E/flutter (21269): <asynchronous suspension>
Following is my user services code:
// #dart=2.9
import 'package:cloud_firestore/cloud_firestore.dart';
class UserServices{
String collection ='users';
FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<void> createUserData(Map<String, dynamic> values)async{
String id= values['id'];
await _firestore.collection(collection).doc(id).set(values);
}
Future<void> updateUserData (Map<String, dynamic>values)async{
String id = values['id'];
await _firestore.collection(collection).doc(id).update(values);
}
Future<DocumentSnapshot>getUserById(String id) async{
var result = await _firestore.collection(collection).doc(id).get();
return result;
}
}
and following is my mapscreen code
Padding(
padding: const EdgeInsets.all(15.0),
child: SizedBox(
width: MediaQuery.of(context).size.width-40,
child: AbsorbPointer(
absorbing: _locating ? true : false,
child: TextButton(
style:TextButton.styleFrom(
backgroundColor:_locating ?
Colors.grey: Theme.of(context).primaryColor,
),
onPressed:(){
locationData.savePrefs();
if(_loggedIn==false){
Navigator.pushNamed(context, LoginScreen.id);
}
else{
setState((){
_auth.latitude= locationData.latitude;
_auth.longitude= locationData.longitude;
_auth.address=locationData.selectedAddress.addressLine;
});
_auth.updateUser(
id: user?.uid,
number: user?.phoneNumber,
);
}
},
child: Text(
'CONFIRM LOCATION',
style: TextStyle(
color: Colors.white,
),
),
),
),
),
),
and following is my appBarcode
class _MyAppBarState extends State<MyAppBar> {
String _location= '';
String _address= '';
#override
void initState() {
getPrefs();
super.initState();
}
getPrefs()async{
SharedPreferences prefs= await SharedPreferences.getInstance();
String location= prefs.getString('location');
String address= prefs.getString('address');
setState((){
_location= location;
_address= address;
});
}
#override
Widget build(BuildContext context) {
final locationData =Provider.of<LocationProvider>(context);
return AppBar(
automaticallyImplyLeading: true,
elevation: 0.0,
title: TextButton(
onPressed:(){
locationData.getCurrentPosition();
if(locationData.permissionAllowed==true){
Navigator.pushNamed(context, MapScreen.id);
}
else{
print('Permission not Allowed');
}
},
child:Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children:[
Flexible(
child: Text(
_location == null? 'Address not set' : _location,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
),
Icon(
Icons.edit_outlined,
color: Colors.white,
size:15,
),
],
),
Flexible(child: Text(
_address,
overflow:TextOverflow.ellipsis,
style:TextStyle(
color:Colors.white,
fontSize:12,
),
),
),
],
),
),
It looks like you're calling update on a reference to a non-existing document, which is not allowed in Cloud Firestore.
If you want to either create the document if it doesn't exist yet, or update the document if is does exist already, you can use SetOptions(merge: true) with set() like this:
Future<void> updateUserData (Map<String, dynamic>values)async{
String id = values['id'];
await _firestore.collection(collection).doc(id).set(values, SetOptions(merge: true));
}
Also see the FlutterFire documentation on adding documents.

Flutter most effective way to retrieve data from firebase in a Tab Navigation

I want to receive data for month week and day (day as default) from my firebase firestore.
The above image shows ma Tab Ui widget. Each of the tabs should give me data which I show users in a FutureBuilder with ListView.Builder.
I'm searching for a powerful way to display my data since week and month is not selected I dont have to load the content in the first step Also my request to firebase is always the same, only the date is changing. Im thankful for a nice and powerful solution.
Also Im not sure if this is the right approach, the data I'm requesting here is infinite in the future. How to work with that?
This is my request:
getData(DataNotifier dataNotifier) async {
// demo data only
List<Data> _dataList = [];
DateTime _now = DateTime.now();
DateTime _start = DateTime(_now.year, _now.month - 1, 1, 0, 0); // <- This will change
QuerySnapshot snapshot = await db
.collection('data')
.where('dateWhenProofed', isGreaterThanOrEqualTo: _start)
.limit(30)
.get()
.catchError((error) => print("---- Failed: $error"));
snapshot.docs.forEach((document) {
Data data = Data.fromJson(document.data());
_dataList.add(data);
});
dataNotifier.datalist = _dataList;
}
And I want to display my data as List below the Tabs.
These are my tabs:
tabs: [
Tab(
child: Padding(
padding: const EdgeInsets.fromLTRB(
5, 0, 5, 0),
child: Text(
'Heute',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500),
),
),
),
Tab(
child: Padding(
padding: const EdgeInsets.fromLTRB(
5, 0, 5, 0),
child: Text(
'Woche',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500),
),
),
),
Tab(
child: Padding(
padding: const EdgeInsets.fromLTRB(
5, 0, 5, 0),
child: Text(
'Monat',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500),
),
),
),
],
controller: _tabController,
isScrollable: true,
indicatorWeight: 0.0,
onTap: (){}, <---- we can do something here
)
,
There's Timestamp field in Firebase and you can use it for calculating whether the data is in a given boundary.
you can add timestamp value to your data:
Timestamp.now()
for example,
Timestamp get timeLimit {
final limit = DateTime.now().subtract(const Duration(days: 1));
return Timestamp.fromDate(limit);
}
you can get the lower limit of timestamp value that is 1day from the moment when you query.
Then
QuerySnapshot snapshot = await db
.collection('data')
.where('timestamp', isGreaterThanOrEqualTo: timeLimit)
.limit(30)

Error Dart/Flutter: 'context != null': is not true

I am trying to apply a dialog alert every time the item is duplicated but when I do the test it ends up giving this error, does anyone have any tips on how to fix this?
void SalvarMensagem() async {
// select id_armarios from armarios where numero_serie = '$_numeroSerie'
this._status = _status;
_numeroSerie = _status.substring(48, 80);
final QuerySnapshot result = await Future.value(Firestore.instance
.collection("lockers")
.where("numero_serie", isEqualTo: "$_numeroSerie")
.limit(1)
.getDocuments());
final List<DocumentSnapshot> documents = result.documents;
if (documents.length == 1) {
duplicado(context);
} else {
await Firestore.instance
.collection("lockers")
.document()
.setData({"numero_serie": _numeroSerie});
}
}
duplicado(BuildContext context){
Alert(
context: context,
type: AlertType.error,
title: "QR Code já cadastrado",
buttons: [
DialogButton(
child: Text(
"OK",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
color: Colors.lightBlueAccent,
width: 120,
)
],
).show();
}
Error:
E/flutter ( 9129): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: 'package:flutter/src/widgets/localizations.dart': Failed assertion: line 446 pos 12: 'context != null': is not true.
duplicate(context, title, content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(
title,
),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: new Text(
content,
),
),
actions: <Widget>[
new FlatButton(
child: new Text(
"OK",
style: TextStyle(color: Colors.white),
),
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.lightBlueAccent,
),
],
);
},
);
}
Change your alert function and call it with duplicate(context,"QR Code já cadastrado","The content you wanted or delete it") it should be okay. You can change title and content with function parameters.

Resources