A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 'const' - firebase

const homeScreenItems = [
FeedScreen(),
SearchScreen(),
AddPostScreen(),
Text('notification'),
ProfileScreen(uid: FirebaseAuth.instance.currentUser!.uid),
];
above code is my global variable page.
I want to pass uid I stored in Firestore to ProfileScreen() but I am getting the above titled error i.e A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 'const'.
I have declared uid as final in my ProfileScreen() but still I am getting the above error
//here is the code of ProfileScreen()
class ProfileScreen extends StatefulWidget {
final String uid;
const ProfileScreen({Key? key,required this.uid}) : super(key: key);
#override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
var userData = {};
#override
void initState() {
getUserData();
super.initState();
}
getUserData() async {
try {
var snap = await FirebaseFirestore.instance
.collection('users')
.doc(widget.uid)
.get();
setState(() {
userData = snap.data()!;
});
} catch (e) {
showSnakBar(e.toString(), context);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: mobileBackgroundColor,
title: Text(userData['name']),
centerTitle: false,
),
body: ListView(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Row(
children: [
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
'https://images.unsplash.com/photo-1647185255712-b5b8687b2a25?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1722&q=80',
),
),
Expanded(
flex: 1,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: [
buildStatColumn(20, 'posts'),
buildStatColumn(150, 'followers'),
buildStatColumn(10, 'following'),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FollowButton(
backgroundColor: mobileBackgroundColor,
borderColor: Colors.grey,
text: 'Edit Profile',
textColor: primaryColor,
function: () {},
),
],
),
],
),
),
],
),
Container(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(top: 15),
child: Text(
'username',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
),
Container(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(top: 1),
child: Text('some bio'),
),
),
],
),
),
const Divider(),
],
),
);
}
Column buildStatColumn(int num, String lable) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
num.toString(),
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Container(
margin: const EdgeInsets.only(top: 4),
child: Text(
lable,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
),
],
);
}
}

The issue here is that you're using const in homeScreenItems - this sets the variable constant during compile-time and can't be changed. It's usually used for fixed values like Text widgets with fixed String values.
Also, utilizing the bang (!) operator doesn't guarantee that the value won't be null. This only assures the compiler that the value is not null.
Depending on your use-case, you can remove the const from homeScreenItems and add ProfileScreen() once the user has signed-in and you're able to fetch FirebaseAuth.instance.currentUser.
List homeScreenItems = [
FeedScreen(),
SearchScreen(),
AddPostScreen(),
Text('notification'),
];
...
if(FirebaseAuth.instance.currentUser != null){
homeScreenItems.add(ProfileScreen(uid: FirebaseAuth.instance.currentUser!.uid));
}

Related

Data is not being saved at Firebase nor is being retrieved from the firebase

There was no problem saving data into firebase until today. I think this is the same code i use most of the time to store the data in the firebase but strangely the collection " LoanFriends" is not being saved at the firebase. I may be missing some minute details.
The following code doesn't generate any error in the android studio but the data is not being saved.
The code is as follows:
import 'package:budgetapp/ExtractedWidgets/dialog_field.dart';
import 'package:budgetapp/constant.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class WalletScreen extends StatelessWidget {
static String id = 'wallet_screen';
TextEditingController _controllername = TextEditingController();
TextEditingController _controlleraddress =TextEditingController();
TextEditingController _controllerphoneno = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('My Wallet',style: kheadertext),
elevation: 0,
actions: [IconButton(onPressed: (){}, icon: Icon(Icons.notifications_sharp),),],
),
body: Column(
children: [
Container(
height: 200,
decoration: containerdecoration.copyWith( borderRadius: BorderRadius.circular(32.0),),
margin: EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
padding: EdgeInsets.only(left: 35),
child: Row(
children: [
Text('Balance',style: kmyTextstyle.copyWith(fontSize: 25),),
SizedBox(width: 200,),
Icon(FontAwesomeIcons.moneyBill,
color: Colors.white,),
],
),
),
),
Expanded(
child: Container(
padding: EdgeInsets.only(left: 35),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Rs. ', style: kmyTextstyle.copyWith(fontSize: 35),),
SizedBox(width: 5,),
Text("25000",style: kmyTextstyle.copyWith(fontSize: 35),),
],),
),
),
Expanded(
child: Container(
padding: EdgeInsets.only(left: 35),
child: Row(
children: [
Text('My wallet information',style: kmyTextstyle.copyWith(fontSize: 15),),
SizedBox(width: 150,),
Icon(FontAwesomeIcons.ccMastercard,
color: Colors.white,),
],
),
),
),
],
)
),
Text("Loan Mechanism",style: kheadertext.copyWith(fontSize: 20),),
SizedBox(height: 8,),
StreamBuilder<QuerySnapshot?>(
stream: FirebaseFirestore.instance.collection('LoanFriends').snapshots(),
builder: (context,snapshot){
if(!snapshot.hasData){
return CircularProgressIndicator();
}
else {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
itemBuilder:(context, index){
return Text(snapshot.data!.docs[index]['name']);
});
}
}
),
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: Color(0xFFcdc3ff),
onPressed: (){
showAlertDialog(context);
},
child: Icon(Icons.add),
),
);
}
void showAlertDialog(BuildContext context) {
showDialog(context: context, builder: (context){
return AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(32), ),
content: Container(
height: MediaQuery.of(context).size.height*0.4,
width: MediaQuery.of(context).size.width*0.5,
child: Column(
children: [
Dialogfield(hinttext: 'Enter name', controller: _controllername, textInputtype: TextInputType.name),
Dialogfield(hinttext: 'Enter address', controller: _controlleraddress, textInputtype: TextInputType.text),
Dialogfield(hinttext: 'Enter phonenumber', controller: _controllerphoneno, textInputtype: TextInputType.number),
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Color(0xFFcdc3ff)),
),
onPressed: (){
Map<String, dynamic> mapdata = {'name': _controllername, 'address': _controlleraddress, 'phonenumber': _controllerphoneno
};
FirebaseFirestore.instance.collection('LoanFriends').add(mapdata);
_controllername.text ='';
_controlleraddress.text='';
_controllerphoneno.text ='';
Navigator.pop(context);
},
child: Text('Add User',style: kmyTextstyle.copyWith(fontSize: 15),),),
],
),
),
);
});
}
}
You need to access the text property of a controller. You cant refer to controller directly.
Change this line:
Map<String, dynamic> mapdata = {'name': _controllername, 'address': _controlleraddress, 'phonenumber': _controllerphoneno
into this line:
Map<String, dynamic> mapdata = {'name': _controllername.text, 'address': _controlleraddress.text, 'phonenumber': _controllerphoneno.text

Flutter: Firebase Storage is not uploading multiple images, it always repeat the same path?

class CategoryScreen extends StatefulWidget {
static const routeName = '/category-screen';
#override
_CategoryScreenState createState() => _CategoryScreenState();
}
class _CategoryScreenState extends State<CategoryScreen> {
#override
Widget build(BuildContext context) {
//from co_detai_screen.dart
final companyId = ModalRoute.of(context).settings.arguments as String;
//
final _form = GlobalKey<FormState>();
String _car = '';
String _carModel = '';
File carImage;
String ranDom = randomBetween(0, 300).toString();
void _submitCarCategory() async{
final isValid = _form.currentState.validate();
if(isValid){
_form.currentState.save();
//.... upload image here
/*===============================Here is firebase storage work==============================*/
final ref = FirebaseStorage.instance.ref().child('cars').child(ranDom + '.jpg');
await ref.putFile(carImage);
//kan fe .onComplete ba3ed (image)**strong text**
//.... upload image here
//... now want to get this image into the firestore
final url = await ref.getDownloadURL();
//... now want to get this image into the firestore
FirebaseFirestore.instance.collection('companies').doc(companyId).collection('category').doc().set(({
'carName': _car,
'carModel': _carModel,
'car_image': url
}));
Navigator.of(context).pop();
}
}
void _pickedImage(File image){
carImage = image;
}
void _showDialog(){
showDialog(context: context, builder: (context)=> AlertDialog(
title: Text('Add Category'),
content: SingleChildScrollView(
child: Form(
key: _form,
child: Container(
height: 450,
width: double.infinity,
padding: EdgeInsets.all(20),
child: Column(
children: [
Text('Add Category', style: TextStyle(fontSize: 16),),
SizedBox(height: 10,),
UserImagePicker(_pickedImage),
TextFormField(decoration: InputDecoration(labelText: 'Car'),
onSaved: (value){
_car = value;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Car model'),
onSaved: (value){
_carModel = value;
},
),
SizedBox(height: 20,),
FlatButton(
onPressed: (){
_submitCarCategory();
},
child: Text('Add'),
color: Colors.indigo,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)
),
),
],
),
),
),
),
),
);
}
return FutureBuilder(
future: FirebaseFirestore.instance.collection('companies').doc(companyId).get(),
builder: (ctx, futureSnapshot){
if(futureSnapshot.hasData){
return Scaffold(
appBar: AppBar(title: Row(
children: [
Text(futureSnapshot.data['coname']),
SizedBox(width: 5,),
Text('Category'),
],
),
),
body: Column(
children: [
SizedBox(height: 30,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: FlatButton(
onPressed: ()=> _showDialog(),
child: Text('Add Category'),
color: Colors.indigo,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)
),
),
),
],
),
SizedBox(height: 10,),
Divider(),
SizedBox(height: 10,),
Expanded(
child: CategoryWidget(
//futurebuilder snapshot id
futureSnapshot.data.id
),
),
],
),
);
}else{
return Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
}
);
}
}
Instead of using
String ranDom = randomBetween(0, 300).toString();
Assign a Date and Time(including seconds) to your image name or combination of both ranDom and dateTime.
final ref = FirebaseStorage.instance.ref().child('cars').child(ranDom + DateTime + '.jpg');

Flutter:How to convert Cards UI or View to Individual View Please find the HomeScreen Page code and try to convert to detailed individual view

Flutter:How to convert Cards UI or View to Individual View Please find the HomeScreen Page code and try to convert to detailed individual view
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:gadjet_inventory/Form/ListTiles.dart';
import 'package:gadjet_inventory/main.dart';
import 'package:intl/intl.dart';
import 'package:gadjet_inventory/Form/Data.dart';
import 'UploadData.dart';
import 'package:pdf_flutter/pdf_flutter.dart';
// ignore: must_be_immutable
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<Data> dataList = [];
List<bool> favList = [];
bool searchState = false;
FirebaseAuth auth = FirebaseAuth.instance;
#override
void initState() {
// TODO: implement initState
super.initState();
DatabaseReference referenceData = FirebaseDatabase.instance.reference().child("Data");
referenceData.once().then((DataSnapshot dataSnapShot) {
dataList.clear();
favList.clear();
var keys = dataSnapShot.value.keys;
var values = dataSnapShot.value;
for (var key in keys) {
Data data = new Data(
values [key]['imgUrl'],
values [key]['wcpdfUrl'],
values [key]['ugpdfUrl'],
values [key]['cattegorrytype'],
values [key]['companyname'],
values [key]['modelname'],
values [key]['seriesname'],
values [key]['year'],
key
//key is the uploadid
);
dataList.add(data);
auth.currentUser().then((value) {
DatabaseReference reference = FirebaseDatabase.instance.reference().child("Data").child(key).child("Fav")
.child(value.uid).child("state");
reference.once().then((DataSnapshot snapShot){
if(snapShot.value!=null){
if(snapShot.value=="true"){
favList.add(true);
}else{
favList.add(false);
}
}else{
favList.add(false);
}
});
});
}
Timer(Duration(seconds: 1),(){
setState(() {
//
});
});
});
}
int selectedRadioTile;
String get path => null;
String get title => null;
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreen,
//Color(0xffffffff),
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.blue,
title: new Text("Device Details", style:
TextStyle(fontSize: 20), textAlign: TextAlign.center),
actions: <Widget>[
IconButton(icon: Icon(Icons.refresh, size: 36, color: Colors.white,),
onPressed: () {
//debugPrint("Add New Device Cattegorry");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ListTiles();
}
)
); //
},
),
IconButton(icon: Icon(Icons.home, size: 36, color: Colors.white,),
onPressed: () {
//debugPrint("Add New Device Cattegorry");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return MyHomePage();
}
)
); //
},
)
],),
body: dataList.length == 0
? Center(
child: Text("No Data Available", style: TextStyle(fontSize: 30),))
: ListView.builder(
itemCount: dataList.length,
itemBuilder: (_, index) {
return CardUI(dataList[index].imgUrl,dataList[index].wcpdfUrl, dataList[index].cattegorrytype,
dataList[index].companyname, dataList[index].modelname,dataList[index].seriesname,dataList[index].year,
dataList[index].uploadid,index);
}
),
);
}
Widget CardUI(String imgUrl, String wcpdfUrl,String cattegorrytype, String companyname, String modelname,
String seriesname, String year ,
String uploadId,int index) {
return Card(
elevation: 7,
margin: EdgeInsets.all(15),
//color: Color(0xffff2fc3),
color:Colors.blueGrey,
child: Container(
color: Colors.white,
margin: EdgeInsets.all(1.5),
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Image.network(
imgUrl != null
? imgUrl
: '',
width: 500,
height: 500,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text( "Cattegorry Type:- "
"$cattegorrytype",
style: TextStyle(color: Colors.black),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Company Name:- "
"$companyname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Model Name:- "
"$modelname",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Series Name:- "
"$seriesname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Year Of MFG:- "
"$year",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.blue,
child: Text("Warranty Card",
style: TextStyle(fontSize: 18, color: Colors.white),),
),
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text("PDF"),
//subtitle: Text("Upload PDF File"),
/* onChanged: (val) {
filePicker(context);
},*/
activeColor: Colors.red,
),
Padding(padding: EdgeInsets.only(top: 15)),
// _buildPDF1Field(context),
PDF.network(
wcpdfUrl != null
? wcpdfUrl
: '',
width: 600,
height: 1000, placeHolder: Image.asset("assets/images/pdf.png",
height: 600, width: 500),
),
SizedBox(height: 24),
],
),
),
);
}
I have uploaded few text items one imageUrl and one pdf document to firebase storage and able to retrieve them in HomeScreen View (card UI or View (cards list) and List Tile View( with one image and one text, when tapped on it should show each individual view).
Please guide me How to convert to Individual Retrieving page instead of group of vertical cards list.

flutter :sharedpreference retrieving null value [duplicate]

This question already has answers here:
What is a NoSuchMethod error and how do I fix it?
(2 answers)
Closed 2 years ago.
The method 'getStringList' was called on null.
Receiver: null
Tried calling: getStringList("userCart")
The relevant error-causing widget was:
Consumer .the details are stored in firebase,the error occurs when displaying the no of items the user have added to the cart.
the CartItemCounter dart file is that thrown error when calling consumer.initially useCart is given as garbage value when registering in firebase.
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class StoreHome extends StatefulWidget {
#override
_StoreHomeState createState() => _StoreHomeState();
}
class _StoreHomeState extends State<StoreHome> {
SharedPreferences sharedPreferences;
#override
void initState() {
super.initState();
SharedPreferences.getInstance().then((prefs){
setState(() {
sharedPreferences=prefs;
});
});
}
#override
Widget build(BuildContext context) {
final _width=MediaQuery.of(context).size.width;
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("E_shop",style: TextStyle(color:Colors.red,),
),
centerTitle: true,
actions: [
Stack(
children: [
IconButton(icon:Icon(Icons.add_shopping_cart,color: Colors.grey,),
onPressed: (){
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>StoreHome()));
},
),
Positioned(child: Stack(
children: [
Icon(Icons.brightness_1,size: 20.0,
color: Colors.green,),
Positioned(
top: 3.0,
bottom: 4.0,
left:4.0,
child: Consumer<CartItemCounter>(
builder: (context, counter,_){
return Text(
counter.count.toString(),
style:TextStyle(color:Colors.white,fontSize:12.0,fontWeight:FontWeight.w500),
);
},),
),
],
),
),
],
),
],
),
drawer: MyDrawer(),
body: CustomScrollView(
slivers: [
SliverPersistentHeader(
pinned: true,
delegate: SearchBoxDelegate(),
),
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("items").limit(15).orderBy("publishedDate",descending: true).snapshots(),
builder: (context,dataSnapshot){
return !dataSnapshot.hasData
?SliverToBoxAdapter(child: Center(child: circularProgress(),),)
:SliverStaggeredGrid.countBuilder(
crossAxisCount: 1,
itemCount: 5,
staggeredTileBuilder: (c)=>StaggeredTile.fit(1),
itemBuilder: (context,index){
ItemModel model=ItemModel.fromJson(dataSnapshot.data.docs[index].data());
return sourceInfo(model,context);
},
);
},
),
],
),
),
);
}
circularProgress(){
return Container(
alignment: Alignment.center,
padding: EdgeInsets.only(top: 12.0),
child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.lightGreenAccent),),
);
}
Widget sourceInfo(ItemModel model, BuildContext context , {Color background, removeCartFunction}) {
return InkWell(
onTap: (){
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>ProductPage(itemModel:model)));
},
splashColor: Colors.pink,
child: Padding(
padding: EdgeInsets.all(6.0),
child: Container(
height: 300.0,
width: MediaQuery.of(context).size.width,
child: Row(
children: [
Image.network(model.thumbnailUrl ,width:140.0,height: 140.0,),
SizedBox(width: 4.0,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 16.0,),
Container(
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(child: Text(
model?.title ?? '',style: TextStyle(color: Colors.black,fontSize: 14.0),
),
)
],
),
),
SizedBox(height: 5.0,),
Container(
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(child: Text(
model?.shortInfo ?? '',style: TextStyle(color: Colors.black54,fontSize: 12.0),
),
)
],
),
),
SizedBox(height: 20.0,),
Row(
children: [
Container(
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.pink,
),
alignment: Alignment.topLeft,
width: 40.0,
height: 43.0,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"50%",style: TextStyle(
fontSize: 15.0,color: Colors.white,
fontWeight: FontWeight.bold,
),
),
Text(
"OFF",style: TextStyle(
fontSize: 12.0,color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
SizedBox(width: 10.0,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(top: 0.0),
child: Row(
children: [
Text(
"Original Price :%",
style: TextStyle(
fontSize: 14.0,
color: Colors.grey
),
),
Text(
(model?.price??'').toString(),
style: TextStyle(
fontSize: 15.0,
color: Colors.grey,
decoration: TextDecoration.lineThrough,
),
)
],
),
),
Padding(
padding: EdgeInsets.only(top: 5.0),
child: Row(
children: [
Text(
"New Price :%",
style: TextStyle(
fontSize: 16.0,
color: Colors.red,
),
),
Text(
"%",
style: TextStyle(
fontSize: 15.0,
color: Colors.grey,
),
),
Text(
(model.price+model.price).toString(),
style: TextStyle(
fontSize: 15.0,
color: Colors.grey
),
),
],
),
),
],
),
],
),
Flexible(child: Container(
),
),
//to implement cart add/remove remove
Align(
alignment: Alignment.centerRight,
child: removeCartFunction==null
?IconButton(
icon: Icon(Icons.add_shopping_cart,color: Colors.pinkAccent,),
onPressed: (){
checkItemInCart(model.shortInfo,context);
},)
:IconButton(
icon: Icon(Icons.delete),
onPressed: null)
)
],
))
],
),
),
),
);
}
void checkItemInCart(String shortInfoAsId, BuildContext context) {
sharedPreferences.getStringList(EcommerceApp.userCartList).contains(shortInfoAsId)
?Fluttertoast.showToast(msg: "item already in cart")
:addItemToCart(shortInfoAsId,context);
}
addItemToCart(String shortInfoAsId, BuildContext context) {
List tempCartList=sharedPreferences.getStringList(EcommerceApp.userCartList);
tempCartList.add(shortInfoAsId);
FirebaseFirestore.instance.collection("users").doc(sharedPreferences.getString(EcommerceApp.userUID))
.update({
EcommerceApp.userCartList: tempCartList,
}).then((value){
Fluttertoast.showToast(msg: "Item added to cart successfully");
sharedPreferences.setStringList(EcommerceApp.userCartList, tempCartList);
Provider.of<CartItemCounter>(context,listen: false).displayResult();
});
}
}```
the CartItemCounter dart file is that thrown error when calling consumer<cartitemcounter>.initially useCart is given as garbage value when registering in firebase.
```class CartItemCounter extends ChangeNotifier{
static SharedPreferences sharedPreferences;
int _counter=sharedPreferences.getStringList("userCart").length-1;
int get count=>_counter;
Future<void> displayResult() async{
int _counter=sharedPreferences.getStringList("userCart").length-1;
await Future.delayed(const Duration(milliseconds: 100),(){
notifyListeners();
});
}
}```
The method 'getStringList' was called on null.
Receiver: null
Tried calling: getStringList("userCart")
The relevant error-causing widget was:
Consumer<CartItemCounter> .the details are stored in firebase,the error occurs when displaying the no of items the user have added to the cart.
The error:
getStringList("...") was called on null
implies that the method was called on a null object which means that you are trying to call sharedPrefs.getStringList()
but, sharedPrefs is null at the moment as it has not been loaded yet. Hence, you encounter the problem. A simple hack to solve this problem:
#override
Widget build(BuildContext context) {
final _width=MediaQuery.of(context).size.width;
return SafeArea(
child:
sharedPrefs == null? // If sharedPrefs is not retreived yet
Scaffold(body: Center(child: Text("Hold on :)"))): // Show this widget
Scaffold( // Else do your normal job
appBar: AppBar(
title: Text("E_shop",style: TextStyle(color:Colors.red,),
),
......... and so on..

How to pass an initial value to the Timer widget - Flutter

I have this timer from this package https://pub.dev/packages/stop_watch_timer
and I am trying to pass an initial value to it:
DateTime dateNow = DateTime.now () // this is my current Time.
Duration initialTime;
initialTime = dateNow.difference (timeStampfromFirestore.toDate ());
initialTime -> this is the value with which I want the Timer to start, but I have not been able to understand how the package works
for example:
the timer right now starts like this: 00:00:00
I'm trying to make it start like this for example: 00:15:00
where initialTime = 00:15:00
import 'package:flutter/material.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final StopWatchTimer _stopWatchTimer = StopWatchTimer(
onChange: (value) => print('onChange $value'),
onChangeSecond: (value) => print('onChangeSecond $value'),
onChangeMinute: (value) => print('onChangeMinute $value'),
);
final _scrollController = ScrollController();
#override
void initState() {
super.initState();
_stopWatchTimer.rawTime.listen((value) =>
print('rawTime $value ${StopWatchTimer.getDisplayTime(value)}'));
_stopWatchTimer.minuteTime.listen((value) => print('minuteTime $value'));
_stopWatchTimer.secondTime.listen((value) => print('secondTime $value'));
_stopWatchTimer.records.listen((value) => print('records $value'));
_stopWatchTimer.onExecute.add(StopWatchExecute.start);
/// Can be set preset time. This case is "00:01.23".
// _stopWatchTimer.setPresetTime(mSec: 1234);
}
#override
void dispose() async {
super.dispose();
await _stopWatchTimer.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
/// Display stop watch time
Padding(
padding: const EdgeInsets.only(bottom: 0),
child: StreamBuilder<int>(
stream: _stopWatchTimer.rawTime,
initialData: _stopWatchTimer.rawTime.value,
builder: (context, snap) {
final value = snap.data;
final displayTime = StopWatchTimer.getDisplayTime(value);
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Text(
displayTime,
style: TextStyle(
fontSize: 40,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: Text(
value.toString(),
style: TextStyle(
fontSize: 16,
fontFamily: 'Helvetica',
fontWeight: FontWeight.w400),
),
),
],
);
},
),
),
/// Display every minute.
Padding(
padding: const EdgeInsets.only(bottom: 0),
child: StreamBuilder<int>(
stream: _stopWatchTimer.minuteTime,
initialData: _stopWatchTimer.minuteTime.value,
builder: (context, snap) {
final value = snap.data;
print('Listen every minute. $value');
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text(
'minute',
style: TextStyle(
fontSize: 17,
fontFamily: 'Helvetica',
),
),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 4),
child: Text(
value.toString(),
style: TextStyle(
fontSize: 30,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
],
)),
],
);
},
),
),
/// Display every second.
Padding(
padding: const EdgeInsets.only(bottom: 0),
child: StreamBuilder<int>(
stream: _stopWatchTimer.secondTime,
initialData: _stopWatchTimer.secondTime.value,
builder: (context, snap) {
final value = snap.data;
print('Listen every second. $value');
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text(
'second',
style: TextStyle(
fontSize: 17,
fontFamily: 'Helvetica',
),
),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 4),
child: Text(
value.toString(),
style: TextStyle(
fontSize: 30,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
],
)),
],
);
},
),
),
/// Lap time.
Container(
height: 120,
margin: const EdgeInsets.all(8),
child: StreamBuilder<List<StopWatchRecord>>(
stream: _stopWatchTimer.records,
initialData: _stopWatchTimer.records.value,
builder: (context, snap) {
final value = snap.data;
if (value.isEmpty) {
return Container();
}
Future.delayed(const Duration(milliseconds: 100), () {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut);
});
print('Listen records. $value');
return ListView.builder(
controller: _scrollController,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
final data = value[index];
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Text(
'${index + 1} ${data.displayTime}',
style: TextStyle(
fontSize: 17,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
const Divider(
height: 1,
)
],
);
},
itemCount: value.length,
);
},
),
),
],
),
),
),
);
}
}
Can be used setPresetTime interface.
Please see.
https://github.com/hukusuke1007/stop_watch_timer
Set Preset Time
Can be set preset time. This case is "00:01.23". When timer is idle state, can be set this.
// Set Millisecond.
_stopWatchTimer.setPresetTime(mSec: 1234);
// Set Hours. (ex. 1 hours)
_stopWatchTimer.setPresetHoursTime(1);
// Set Minute. (ex. 30 minute)
_stopWatchTimer.setPresetMinuteTime(30);
// Set Second. (ex. 120 second)
_stopWatchTimer.setPresetSecondTime(120);

Resources