Related
i met a error on val... It says ,
A value of type 'String?' can't be assigned to a variable of type
'String'. Try changing the type of the variable, or casting the
right-hand type to 'String'.
got error on this ,
this code is in below full code
onChanged: (val) => setState(
() => _applyleavevalueChanged = val),
validator: (val) {
setState(
() => _applyleavevalueToValidate = val);
return null;
},
onSaved: (val) => setState(
() => _applyleavevalueSaved = val),
i met a error on val... It says ,
A value of type 'String?' can't be assigned to a variable of type
'String'. Try changing the type of the variable, or casting the
right-hand type to 'String'.
this is my full source code.....
File : leaveapply.dart
import 'package:date_time_picker/date_time_picker.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import './LeaveApply/BouncingButton.dart';
import './LeaveApply/leave_history.dart';
import 'LeaveApply/LeaveHistoryCard.dart';
import 'LeaveApply/datepicker.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: LeaveApply(),
title: 'Leave Apply',
));
}
class LeaveApply extends StatefulWidget {
#override
_LeaveApplyState createState() => _LeaveApplyState();
}
class _LeaveApplyState extends State<LeaveApply>
with SingleTickerProviderStateMixin {
late Animation animation, delayedAnimation, muchDelayedAnimation, LeftCurve;
late AnimationController animationController;
final searchFieldController = TextEditingController();
late TextEditingController _applyleavecontroller;
String _applyleavevalueChanged = '';
String _applyleavevalueToValidate = '';
String _applyleavevalueSaved = '';
late TextEditingController _fromcontroller;
String _fromvalueChanged = '';
String _fromvalueToValidate = '';
String _fromvalueSaved = '';
late TextEditingController _tocontroller;
String _tovalueChanged = '';
String _tovalueToValidate = '';
String _tovalueSaved = '';
#override
void initState() {
// ignore: todo
// TODO: implement initState
super.initState();
//SystemChrome.setEnabledSystemUIOverlays([]);
_applyleavecontroller =
TextEditingController(text: DateTime.now().toString());
_fromcontroller = TextEditingController(text: DateTime.now().toString());
_tocontroller = TextEditingController(text: DateTime.now().toString());
animationController =
AnimationController(duration: Duration(seconds: 3), vsync: this);
animation = Tween(begin: -1.0, end: 0.0).animate(CurvedAnimation(
parent: animationController, curve: Curves.fastOutSlowIn));
delayedAnimation = Tween(begin: 1.0, end: 0.0).animate(CurvedAnimation(
parent: animationController,
curve: Interval(0.2, 0.5, curve: Curves.fastOutSlowIn)));
muchDelayedAnimation = Tween(begin: -1.0, end: 0.0).animate(CurvedAnimation(
parent: animationController,
curve: Interval(0.3, 0.5, curve: Curves.fastOutSlowIn)));
}
#override
void dispose() {
// ignore: todo
// TODO: implement dispose
animationController.dispose();
super.dispose();
}
final GlobalKey<FormState> _formkey = new GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
animationController.forward();
final double width = MediaQuery.of(context).size.width;
final double height = MediaQuery.of(context).size.height;
final GlobalKey<ScaffoldState> _scaffoldKey =
new GlobalKey<ScaffoldState>();
return AnimatedBuilder(
animation: animationController,
builder: (BuildContext context, Widget? child) {
final GlobalKey<ScaffoldState> _scaffoldKey =
new GlobalKey<ScaffoldState>();
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
'Apply Leave',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
leading: new IconButton(
icon: new Icon(
Icons.arrow_back_ios,
color: Colors.black87,
size: 18.0,
),
onPressed: () => Navigator.of(context).pop(),
),
centerTitle: true,
elevation: 1.0,
),
body: Form(
key: _formkey,
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 15.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Divider(
color: Colors.black.withOpacity(0.5),
height: 1,
),
SizedBox(
height: height * 0.05,
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Text(
"Apply Leave Date",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
Padding(
padding: EdgeInsets.only(
top: 13,
),
child: Container(
// height: height * 0.06,
padding: EdgeInsets.only(
left: 10,
),
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(5),
),
child: Row(
children: [
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Container(
width: width * 0.75,
child: DateTimePicker(
type: DateTimePickerType.date,
dateMask: 'dd/MM/yyyy',
controller: _applyleavecontroller,
//initialValue: _initialValue,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
calendarTitle: "Leave Date",
confirmText: "Confirm",
enableSuggestions: true,
//locale: Locale('en', 'US'),
onChanged: (val) => setState(
() => _applyleavevalueChanged = val),
validator: (val) {
setState(
() => _applyleavevalueToValidate = val);
return null;
},
onSaved: (val) => setState(
() => _applyleavevalueSaved = val),
),
),
),
Transform(
transform: Matrix4.translationValues(
delayedAnimation.value * width, 0, 0),
child: Icon(
Icons.calendar_today,
color: Colors.black,
),
),
],
),
),
),
SizedBox(
height: height * 0.03,
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Text(
"Choose Leave Type",
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 14,
),
),
),
SizedBox(
height: height * 0.02,
),
Transform(
transform: Matrix4.translationValues(
delayedAnimation.value * width, 0, 0),
child: DropdownSearch<String>(
validator: (v) => v == null ? "required field" : null,
hint: "Please Select Leave type",
mode: Mode.MENU,
showSelectedItems: true,
items: [
"Medical",
"Family",
"Sick",
'Function',
'Others'
],
showClearButton: true,
onChanged: print,
),
),
SizedBox(
height: height * 0.05,
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Text(
"Leave Date",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
Padding(
padding: EdgeInsets.only(
top: 13,
),
child: Container(
// height: height * 0.06,
padding: EdgeInsets.only(
left: 10,
),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white38,
borderRadius: BorderRadius.circular(5),
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
color: Colors.black12,
)
]),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Icon(
Icons.calendar_today,
color: Colors.black,
),
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Container(
padding: const EdgeInsets.only(left: 4.0),
width: width * 0.28,
decoration: BoxDecoration(
color: Colors.white38,
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
blurRadius: 2,
color: Colors.black26,
)
]),
child: CustomDatePicker(
controller: _fromcontroller,
title: "From",
onchanged: (val) =>
setState(() => _fromvalueChanged = val),
validator: (val) {
setState(
() => _fromvalueToValidate = val);
return null;
},
saved: (val) =>
setState(() => _fromvalueSaved = val),
),
),
),
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Icon(
Icons.arrow_forward,
color: Colors.black,
),
),
Transform(
transform: Matrix4.translationValues(
delayedAnimation.value * width, 0, 0),
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Container(
padding: const EdgeInsets.only(left: 4.0),
width: width * 0.28,
decoration: BoxDecoration(
color: Colors.white38,
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
blurRadius: 2,
color: Colors.black26,
)
],
),
child: CustomDatePicker(
controller: _tocontroller,
title: "To",
onchanged: (val) => setState(() {
_tovalueChanged = val;
print(val);
}),
validator: (val) {
setState(() => _tovalueToValidate = val);
return null;
},
saved: (val) =>
setState(() => _tovalueSaved = val),
),
),
),
),
],
),
),
),
SizedBox(
height: height * 0.05,
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Text(
"Apply Leave Date",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
Transform(
transform: Matrix4.translationValues(
delayedAnimation.value * width, 0, 0),
child: Padding(
padding: EdgeInsets.only(
top: 13,
),
child: Container(
// height: height * 0.06,
height: height * 0.25,
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(5),
),
child: TextFormField(
//autofocus: true,
minLines: 1,
maxLines: 10,
keyboardType: TextInputType.multiline,
decoration: InputDecoration(
suffixIcon: searchFieldController.text.isNotEmpty
? IconButton(
icon: Icon(Icons.clear),
onPressed: () => WidgetsBinding.instance
?.addPostFrameCallback((_) =>
searchFieldController.clear()))
: null,
border: InputBorder.none,
contentPadding: EdgeInsets.all(7),
),
),
),
),
),
SizedBox(
height: height * 0.05,
),
Transform(
transform: Matrix4.translationValues(
muchDelayedAnimation.value * width, 0, 0),
child: Text(
"Attach Document",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
Transform(
transform: Matrix4.translationValues(
delayedAnimation.value * width, 0, 0),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () async {},
child: Text(
"Click 📑 to Upload Documents",
style: TextStyle(
color: Color(0xff2876bd),
),
),
),
),
),
SizedBox(
height: 15,
),
Transform(
transform: Matrix4.translationValues(
delayedAnimation.value * width, 0, 0),
child: Bouncing(
onPress: () {},
child: Container(
//height: 20,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Color(0xff2876bd),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Request Leave",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
),
),
SizedBox(
height: 50,
),
Column(
children: [
InkWell(
child: Text(
'LeaveHistory',
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LeaveHistory(
// leavetype: '',
// description: '',
// status: '',
// requesteddate: '',
// verifieddate: '',
)),
);
},
)
],
),
SizedBox(
height: 50,
)
],
),
),
),
),
);
},
);
}
}
The value type of _applyleavevalueChanged is String and
the value type of val is String?
if val can be null
_applyleavevalueChanged = val ?? ''; // '' is the default value in case val is null
or
if (val != null) {
_applyleavevalueChanged = val!; // ! mark that the val is definitely not null
}
The error you get came from null-safety, the type String? means that it could be either a String, or null, but your variable only accepts a String, and no null.
For this, you can "force" the use of 'non-null' variable by adding a ! at the end of your variable, but be careful when doing this.
_applyleavevalueToValidate = val!
You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety.
https://api.flutter.dev/flutter/material/DropdownButton-class.html.
You can simply set default value like this. For example,
String? a;
String x = a ?? "default value";
I am trying to implement a review page for products.
I trying to show the products images in a expansionTile (see second image).
Under the expansionTile I add my buttons.
My problem:
To show the expansionTile list I must give the container a fix height.
But if I have less images in my list the screen show a white space (second image).
How can I make the container height dynamic to hide the white space?
Here my example:
If I add some pictures my screen looks like this.
How I can hide the white space between list and buttons?
Here my Code:
Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width * 0.8,
child: ListView(
children: [
ExpansionTile(
title: Text('Pictures'),
onExpansionChanged: (value) {
setState(
() {},
);
},
children: List<Widget>.generate(
_imageList.length,
(index) => ListTile(
title: Text(_imageList[0]
.path
.split('/')
.last
.length >
25
? _imageList[0]
.path
.split('/')
.last
.substring(0, 25) +
'...'
: _imageList[index].path.split('/').last),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
Icons.delete_outline,
size: 20.0,
color: _selected![index]
? Colors.red
: Colors.red,
),
onPressed: () {
setState(() {
_selected![index] =
!_selected![index];
_imageList.removeAt(index);
});
},
),
],
),
),
),
),
],
),
)
Here my full code:
class ReviewPage1 extends StatefulWidget {
//passed paramter
final String _productID;
ReviewPage1(this._productID, {Key? key}) : super(key: key);
#override
_ReviewPage1 createState() => _ReviewPage1(_productID);
}
class _ReviewPage1 extends State<ReviewPage1> {
///passed paramter
final String _productID;
_ReviewPage1(this._productID);
//controller
final TextEditingController _controllerReviewTitle = TextEditingController();
final TextEditingController _controllerReviewDescription =
TextEditingController();
//image
List<File> _imageList = [];
var _image;
var imagePicker;
//list tile color
List<bool>? _selected = [];
//stars
var rating = 1;
#override
void initState() {
super.initState();
imagePicker = new ImagePicker();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: customSubAppBar("Create Review", context),
body: SingleChildScrollView(
child: Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
child: Column(
children: [
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.05,
MediaQuery.of(context).size.width * 0,
null,
),
//text
Row(
children: [
customText(
'Rate your expreince',
Colors.black,
20,
FontWeight.bold,
null,
),
],
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.02,
MediaQuery.of(context).size.width * 0,
null,
),
//stars rating
Row(
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(4, (index) {
return GestureDetector(
onTap: () {
setState(() {
// Toggle light when tapped.
print('star at index: ' + index.toString());
rating = index + 1;
});
},
child: Padding(
padding: const EdgeInsets.only(right: 8),
child: Icon(
//index < rating ? Icons.star : Icons.star_border,
Icons.star,
size: 30,
color: index < rating
? Theme.of(context).primaryColor
: Colors.black.withOpacity(0.5),
)));
}),
),
Spacer(),
],
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.08,
MediaQuery.of(context).size.width * 0,
null,
),
//text
Row(
children: [
customText(
'Review Title',
Colors.black,
20,
FontWeight.bold,
null,
),
],
),
//textfield review title
customDefaultTextField(
50,
1,
TextInputType.text,
_controllerReviewTitle,
1,
false,
Colors.black87,
Theme.of(context).primaryColor,
false,
Theme.of(context).primaryColor,
0,
0,
Theme.of(context).primaryColor,
0,
0,
'Title *',
'Enter Your Title',
Colors.black12,
2,
0,
Theme.of(context).primaryColor,
2,
0,
null,
0,
0,
0,
0,
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.08,
MediaQuery.of(context).size.width * 0,
null,
),
//text
Row(
children: [
customText(
'Write Review',
Colors.black,
20,
FontWeight.bold,
null,
),
],
),
//textfield review description
customDefaultTextField(
50,
1,
TextInputType.text,
_controllerReviewDescription,
1,
false,
Colors.black87,
Theme.of(context).primaryColor,
false,
Theme.of(context).primaryColor,
0,
0,
Theme.of(context).primaryColor,
0,
0,
'Write your Expreinces *',
'Enter your Expreinces',
Colors.black12,
2,
0,
Theme.of(context).primaryColor,
2,
0,
null,
0,
0,
0,
0,
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.08,
MediaQuery.of(context).size.width * 0,
null,
),
//text
Row(
children: [
customText(
'Enter your picture',
Colors.black,
20,
FontWeight.bold,
null,
),
],
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.03,
MediaQuery.of(context).size.width * 0,
null,
),
//take image
GestureDetector(
onTap: () async {
var source = ImageSource.camera;
XFile? image = await imagePicker.pickImage(
source: source,
imageQuality: 50,
preferredCameraDevice: CameraDevice.front);
setState(
() {
_image = File(image!.path);
_imageList.add(_image);
_selected!.add(false);
},
);
},
child: Stack(
children: [
//icon
Container(
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.1,
decoration: BoxDecoration(
color:
Theme.of(context).primaryColor.withOpacity(0.8),
borderRadius: BorderRadius.all(Radius.circular(8))),
child: Center(
child: customIcon(
Icons.camera_alt_rounded, Colors.black87, 30)),
),
//border
Container(
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.1,
child: DashedRect(
color: Colors.black87,
strokeWidth: 2.0,
gap: 10.0,
),
),
],
),
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.03,
MediaQuery.of(context).size.width * 0,
null,
),
//show images
_imageList.length != 0
? //IntrinsicHeight(
Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width * 0.8,
child: ListView(
children: [
ExpansionTile(
title: Text('Pictures'),
onExpansionChanged: (value) {
setState(
() {},
);
},
children: List<Widget>.generate(
_imageList.length,
(index) => ListTile(
title: Text(_imageList[0]
.path
.split('/')
.last
.length >
25
? _imageList[0]
.path
.split('/')
.last
.substring(0, 25) +
'...'
: _imageList[index].path.split('/').last),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
Icons.delete_outline,
size: 20.0,
color: _selected![index]
? Colors.red
: Colors.red,
),
onPressed: () {
setState(() {
_selected![index] =
!_selected![index];
_imageList.removeAt(index);
});
},
),
],
),
),
),
),
],
),
)
//)
: Container(),
//text cancel
Container(
width: MediaQuery.of(context).size.width * 0.8,
child: TextButton(
child: Text(
'Send Review',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
style: TextButton.styleFrom(
primary: Colors.black,
backgroundColor: Colors.greenAccent[400],
onSurface: Colors.grey,
),
onPressed: () {
if (_checkInputValuesEmpty(
context, _controllerReviewTitle.text, 'title') &&
_checkInputValuesEmpty(
context,
_controllerReviewDescription.text,
'description')) {
final String _userID =
FirebaseAuth.instance.currentUser!.uid;
_uploadFile(_userID, _productID, context, _imageList);
}
},
),
),
//size box
customSizedBox(
MediaQuery.of(context).size.height * 0.01,
MediaQuery.of(context).size.width * 0,
null,
),
//text send review
Container(
width: MediaQuery.of(context).size.width * 0.8,
child: TextButton(
child: Text(
'Cancel',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
style: TextButton.styleFrom(
primary: Colors.black,
backgroundColor: Color.fromRGBO(170, 170, 170, 1),
onSurface: Colors.grey,
),
onPressed: () async {},
),
),
],
),
),
),
),
//sidebar
drawer: CustomSideBar(context),
);
}
//upload review images
Future _uploadFile(_userID, _productID, context, _imageList) async {
var downloadURLs = [];
for (var image in _imageList) {
String url;
String postId = DateTime.now().millisecondsSinceEpoch.toString();
String fileName = 'reviewImage_${_productID}_${postId}';
Reference ref = FirebaseStorage.instance
.ref()
.child("images/review/review_images/" + _productID + '/' + _userID)
.child(fileName);
await ref.putFile(image);
url = fileName;
downloadURLs.add(url);
}
//upload review data
_addReviewData(_productID, downloadURLs, _userID);
}
//add review data in db
_addReviewData(_productID, downloadURLs, _userID) async {
final String _userID = FirebaseAuth.instance.currentUser!.uid;
FirebaseFirestore.instance
.collection('review')
.doc('productID_' + _productID)
.collection("userID_" + _userID)
.doc('review_data')
.set({
'stars': rating,
'title': _controllerReviewTitle.text,
'description': _controllerReviewDescription.text,
'image_url': downloadURLs,
});
//Navigator.of(context).pushReplacement(
// MaterialPageRoute(builder: (context) => VerifyRegisterEmail()));
}
}
_checkInputValuesEmpty(context, text, field) {
if (text.toString().length == 0) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Enter text in field ${field}'),
));
return false;
} else {
return true;
}
}
Can I give the container a dynamic height which has always the same height how the listview with my image names?
try find this place and add after Colum mainAxisAlignment: MainAxisAlignment.start,
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: customSubAppBar("Create Review", context),
body: SingleChildScrollView(
child: Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
App was working perfectly before and then I had to make some changes to allow or restrict calling feature in the app based on subscription level of the user, by passing the variable value from one screen to another using provider.
one Screen 1 i am using :
Future<void> _verifyPuchase(String id) async {
PurchaseDetails purchase = _hasPurchased(id);
if (purchase != null && purchase.status == PurchaseStatus.purchased) {
print(purchase.productID);
if (Platform.isIOS) {
await _iap.completePurchase(purchase);
print('Achats antérieurs........$purchase');
isPuchased = true;
}
isPuchased = true;
checkIsPurchsed(isPurchsed: isPuchased);
} else {
isPuchased = false;
checkIsPurchsed(isPurchsed: isPuchased);
}
}
and have i have a class on screen 1:
class checkIsPurchsed with ChangeNotifier{
bool isPurchsed;
checkIsPurchsed({this.isPurchsed});
notifyListeners();
}
and on screen 5 I have:
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.call), onPressed: () => onJoin("AudioCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.video_call), onPressed: () => onJoin("VideoCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
on screen 5 when i try to open a chat this is what i am getting :
the icon buttons on which i am checking the purchase status appear when chat is opened , but after adding the above mentioned modifications the chat itself isnt opening and instead i am getting the red screen.
Update 1:
class ChatPage extends StatefulWidget {
final User sender;
final String chatId;
final User second;
ChatPage({this.sender, this.chatId, this.second});
#override
_ChatPageState createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
bool isBlocked = false;
final db = Firestore.instance;
CollectionReference chatReference;
final TextEditingController _textController = new TextEditingController();
bool _isWritting = false;
final _scaffoldKey = GlobalKey<ScaffoldState>();
//Ads _ads = new Ads();
#override
void initState() {
//_ads.myInterstitial()
//..load()
//..show();
print("object -${widget.chatId}");
super.initState();
chatReference =
db.collection("chats").document(widget.chatId).collection('messages');
checkblock();
}
var blockedBy;
checkblock() {
chatReference.document('blocked').snapshots().listen((onData) {
if (onData.data != null) {
blockedBy = onData.data['blockedBy'];
if (onData.data['isBlocked']) {
isBlocked = true;
} else {
isBlocked = false;
}
if (mounted) setState(() {});
}
// print(onData.data['blockedBy']);
});
}
List<Widget> generateSenderLayout(DocumentSnapshot documentSnapshot) {
return <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Container(
child: documentSnapshot.data['image_url'] != ''
? InkWell(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Container(
margin: EdgeInsets.only(
top: 2.0, bottom: 2.0, right: 15),
child: Stack(
children: <Widget>[
CachedNetworkImage(
placeholder: (context, url) => Center(
child: CupertinoActivityIndicator(
radius: 10,
),
),
errorWidget: (context, url, error) =>
Icon(Icons.error),
height:
MediaQuery.of(context).size.height * .65,
width: MediaQuery.of(context).size.width * .9,
imageUrl:
documentSnapshot.data['image_url'] ?? '',
fit: BoxFit.fitWidth,
),
Container(
alignment: Alignment.bottomRight,
child:
documentSnapshot.data['isRead'] == false
? Icon(
Icons.done,
color: secondryColor,
size: 15,
)
: Icon(
Icons.done_all,
color: primaryColor,
size: 15,
),
)
],
),
height: 150,
width: 150.0,
color: secondryColor.withOpacity(.5),
padding: EdgeInsets.all(5),
),
Padding(
padding: const EdgeInsets.only(right: 10),
child: Text(
documentSnapshot.data["time"] != null
? DateFormat.yMMMd()
.add_jm()
.format(documentSnapshot.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
)),
)
],
),
onTap: () {
Navigator.of(context).push(
CupertinoPageRoute(
builder: (context) => LargeImage(
documentSnapshot.data['image_url'],
),
),
);
},
)
: Container(
padding: EdgeInsets.symmetric(
horizontal: 15.0, vertical: 10.0),
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.only(
top: 8.0, bottom: 8.0, left: 80.0, right: 10),
decoration: BoxDecoration(
color: primaryColor.withOpacity(.1),
borderRadius: BorderRadius.circular(20)),
child: Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Container(
child: Text(
documentSnapshot.data['text'],
style: TextStyle(
color: Colors.black87,
fontSize: 16.0,
fontWeight: FontWeight.w600,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
documentSnapshot.data["time"] != null
? DateFormat.MMMd()
.add_jm()
.format(documentSnapshot
.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
),
),
SizedBox(
width: 5,
),
documentSnapshot.data['isRead'] == false
? Icon(
Icons.done,
color: secondryColor,
size: 15,
)
: Icon(
Icons.done_all,
color: primaryColor,
size: 15,
)
],
),
],
),
],
)),
),
],
),
),
];
}
_messagesIsRead(documentSnapshot) {
return <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
child: CircleAvatar(
backgroundColor: secondryColor,
radius: 25.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(90),
child: CachedNetworkImage(
imageUrl: widget.second.imageUrl[0] ?? '',
useOldImageOnUrlChange: true,
placeholder: (context, url) => CupertinoActivityIndicator(
radius: 15,
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
),
onTap: () => showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return Info(widget.second, widget.sender, null);
}),
),
],
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: documentSnapshot.data['image_url'] != ''
? InkWell(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Container(
margin: EdgeInsets.only(
top: 2.0, bottom: 2.0, right: 15),
child: CachedNetworkImage(
placeholder: (context, url) => Center(
child: CupertinoActivityIndicator(
radius: 10,
),
),
errorWidget: (context, url, error) =>
Icon(Icons.error),
height: MediaQuery.of(context).size.height * .65,
width: MediaQuery.of(context).size.width * .9,
imageUrl:
documentSnapshot.data['image_url'] ?? '',
fit: BoxFit.fitWidth,
),
height: 150,
width: 150.0,
color: Color.fromRGBO(0, 0, 0, 0.2),
padding: EdgeInsets.all(5),
),
Padding(
padding: const EdgeInsets.only(right: 10),
child: Text(
documentSnapshot.data["time"] != null
? DateFormat.yMMMd()
.add_jm()
.format(documentSnapshot.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
)),
)
],
),
onTap: () {
Navigator.of(context).push(CupertinoPageRoute(
builder: (context) => LargeImage(
documentSnapshot.data['image_url'],
),
));
},
)
: Container(
padding: EdgeInsets.symmetric(
horizontal: 15.0, vertical: 10.0),
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.only(top: 8.0, bottom: 8.0, right: 10),
decoration: BoxDecoration(
color: secondryColor.withOpacity(.3),
borderRadius: BorderRadius.circular(20)),
child: Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Container(
child: Text(
documentSnapshot.data['text'],
style: TextStyle(
color: Colors.black87,
fontSize: 16.0,
fontWeight: FontWeight.w600,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
documentSnapshot.data["time"] != null
? DateFormat.MMMd()
.add_jm()
.format(documentSnapshot
.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
),
),
],
),
],
),
],
)),
),
],
),
),
];
}
List<Widget> generateReceiverLayout(DocumentSnapshot documentSnapshot) {
if (!documentSnapshot.data['isRead']) {
chatReference.document(documentSnapshot.documentID).updateData({
'isRead': true,
});
return _messagesIsRead(documentSnapshot);
}
return _messagesIsRead(documentSnapshot);
}
generateMessages(AsyncSnapshot<QuerySnapshot> snapshot) {
return snapshot.data.documents
.map<Widget>((doc) => Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: doc.data['type'] == "Call"
? [
Text(doc.data["time"] != null
? "${doc.data['text']} : " +
DateFormat.yMMMd()
.add_jm()
.format(doc.data["time"].toDate())
.toString() +
" by ${doc.data['sender_id'] == widget.sender.id ? "You" : "${widget.second.name}"}"
: "")
]
: doc.data['sender_id'] != widget.sender.id
? generateReceiverLayout(
doc,
)
: generateSenderLayout(doc)),
))
.toList();
}
#override
Widget build(BuildContext context) {
ChangeNotifierProvider<checkIsPurchsed>(
create: (context)=>checkblock(),
child: Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
elevation: 0,
title: Text(widget.second.name),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
color: Colors.white,
onPressed: () => Navigator.pop(context),
),
actions: <Widget>[
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.call), onPressed: () => onJoin("AudioCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.video_call), onPressed: () => onJoin("VideoCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
}
The problematic area is:
#override
Widget build(BuildContext context) {
ChangeNotifierProvider<checkIsPurchsed>(
There's no return in front of ChangeNotifierProvider, so it doesn't return a Widget. Correct would be:
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<checkIsPurchsed>(
import 'package:facebook_audience_network/ad/ad_native.dart';
import 'package:facebook_audience_network/facebook_audience_network.dart';
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:social_share/social_share.dart';
import 'package:clipboard_manager/clipboard_manager.dart';
// ignore: camel_case_types
class listview extends StatefulWidget {
const listview({
Key key,
#required this.records,
}) : super(key: key);
final List records;
#override
_listviewState createState() => _listviewState();
}
// ignore: camel_case_types
class _listviewState extends State<listview> {
#override
void initState() {
super.initState();
FacebookAudienceNetwork.init(
testingId: "35e92a63-8102-46a4-b0f5-4fd269e6a13c",
);
// _loadInterstitialAd();
// _loadRewardedVideoAd();
}
// ignore: unused_field
Widget _currentAd = SizedBox(
width: 0.0,
height: 0.0,
);
Widget createNativeAd() {
_showNativeAd() {
_currentAd = FacebookNativeAd(
adType: NativeAdType.NATIVE_AD,
backgroundColor: Colors.blue,
buttonBorderColor: Colors.white,
buttonColor: Colors.deepPurple,
buttonTitleColor: Colors.white,
descriptionColor: Colors.white,
width: double.infinity,
height: 300,
titleColor: Colors.white,
listener: (result, value) {
print("Native Ad: $result --> $value");
},
);
}
return Container(
width: double.infinity,
height: 300,
child: _showNativeAd(),
);
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.widget.records.length,
itemBuilder: (BuildContext context, int index) {
var card = Container(
child: Card(
margin: EdgeInsets.only(bottom: 10),
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(1.0),
),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
print(this.widget.records);
},
child: Image.asset(
"assets/icons/avatar.png",
height: 45,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
(this
.widget
.records[index]['fields']['Publisher Name']
.toString()),
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
(this
.widget
.records[index]['fields']['Date']
.toString()),
style: TextStyle(
fontSize: 12,
),
),
],
),
)
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: MediaQuery.of(context).size.width * 0.90,
// height: MediaQuery.of(context).size.height * 0.20,
decoration: BoxDecoration(
border: Border.all(
color: Colors.purple,
width: 3.0,
),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(18.0),
child: Text(
(this
.widget
.records[index]['fields']['Shayari']
.toString()),
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
SizedBox(
height: 5,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
GestureDetector(
onTap: () {
ClipboardManager.copyToClipBoard(this
.widget
.records[index]['fields']['Shayari']
.toString())
.then((result) {
final snackBar = SnackBar(
content: Text('Copied to Clipboard'),
);
Scaffold.of(context).showSnackBar(snackBar);
});
print(this
.widget
.records[index]['fields']['Shayari']
.toString());
},
child: Image.asset(
"assets/icons/copy.png",
height: 25,
),
),
GestureDetector(
onTap: () async {
SocialShare.checkInstalledAppsForShare().then(
(data) {
print(data.toString());
},
);
},
child: Image.asset(
"assets/icons/whatsapp.png",
height: 35,
),
),
GestureDetector(
onTap: () async {
Share.share("Please Share https://google.com");
},
child: Image.asset(
"assets/icons/share.png",
height: 25,
),
),
],
),
SizedBox(
height: 5,
),
],
),
),
);
return Column(
children: [
card,
index != 0 && index % 5 == 0
? /* Its Show When Value True*/ createNativeAd()
: /* Its Show When Value false*/ Container()
],
);
},
);
}
}
I Am Having This Error setState() or markNeedsBuild() called during build.
I Try To Call Facebook Native Ads Between My Dynamic List View But Showing this error when I call native ad createNativeAd This is My Widget Where I set Native ad
This is code where I call ad
** return Column(
children: [
card,
index != 0 && index % 5 == 0
? /* Its Show When Value True*/ createNativeAd()
: /* Its Show When Value false*/ Container()
],
);
},
);**
Why do buttons in Flutter tend to align their children to the centre when they are placed in list views?
For example:
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index){
return MaterialButton(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello"),
],
));
}
),
);
}
}
This would result in ten hellos spaced evenly by the default height of the button, but they would be centered; even though I used the CrossAxisAlignment.start property in a column.
Here is the image:
But when I replace the MaterialButton with a Container they are aligned to the start to the column as wanted.
When I just remove the ListView.Builder I get 'hello' aligned to the start.
The same thing happens with the rest of the buttons.
Is there a way to make buttons in list views not have centered children inside them?
Edit: the example was fixed by #Harry but it didn't fix my exact code
here is my code: I try to created a list of widgets outside and use a function to add my list items into that list and return a list view through the ActivitiesList widget
import 'package:flutter/material.dart';
import 'package:list_them_out/models/activities.dart';
import 'package:provider/provider.dart';
class ActivitiesList extends StatefulWidget {
#override
_ActivitiesListState createState() => _ActivitiesListState();
}
double conBorderRadius = 30;
class _ActivitiesListState extends State<ActivitiesList> {
List<Widget> itemData = [];
void getData(context) {
double cardHeight = MediaQuery.of(context).size.height * 0.3;
double cardWidth = MediaQuery.of(context).size.width * 0.97;
final activities = Provider.of<List<Activity>>(context);
activities == null
// ignore: unnecessary_statements
? null
: setState(() {
itemData = [];
});
activities == null
// ignore: unnecessary_statements
? null
: setState(() {
activities.forEach((element) {
itemData.add(Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Container(
width: cardWidth,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(conBorderRadius),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Colors.lightGreen[300],
Colors.lightBlue[300],
]
),
boxShadow: [
BoxShadow(
color: Colors.grey[600],
offset: Offset(4.0, 4.0),
blurRadius: 15,
spreadRadius: 1),
BoxShadow(
color: Colors.white,
offset: Offset(-4.0, -4.0),
blurRadius: 15,
spreadRadius: 1),
]),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(conBorderRadius),
child: MaterialButton(
splashColor: HSLColor.fromColor(Colors.green).toColor(),
onPressed: () {},
child: Align(
alignment: Alignment.centerLeft,
child: Container(
child: Padding(
padding: EdgeInsets.only(top: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: cardWidth * 0.61,
child: Text(
element.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.grey[600],
fontSize: 25,
fontWeight: FontWeight.w500,
letterSpacing: 1,
),
),
),
Padding(
padding: EdgeInsets.only(top: cardHeight * 0.09, left: cardWidth * 0.03),
child: Container(
width: cardWidth * 0.48,
child: RichText(
maxLines: 2,
overflow: TextOverflow.ellipsis,
text: TextSpan(children: [
TextSpan(
text: "Start: ",
style: TextStyle(
color: Colors.grey[800],
fontSize: 20,
fontWeight: FontWeight.w400,
letterSpacing: 1),
),
TextSpan(
text: element.time,
style: TextStyle(
color: Colors.black87,
fontWeight: FontWeight.w300,
fontSize: 20,
))
]),
),
),
),
SizedBox(height: cardHeight * 0.06,),
Row(
children: [
IconButton(icon: Icon(Icons.comment),
onPressed: () => null,
color: Colors.grey[600],
),
Padding(
padding: EdgeInsets.only(bottom: 5),
child: Text("Comments", style: TextStyle(color: Colors.grey[600], fontSize: 20, fontWeight: FontWeight.w300, letterSpacing: 1),),
)
],
)
],
),
),),
),
),
),
Positioned(
right: 0,
bottom: 0,
top: 0,
child: ClipPath(
clipper: MyClip(radius: conBorderRadius),
child: Container(
height: cardHeight,
width: cardWidth * 0.45,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Colors.grey[300],
Colors.lightBlue[100].withOpacity(0.5)
])),
),
),
),
Positioned(
right: cardWidth * 0.05,
bottom: 20,
child: Container(
child: Text("Hello"),
),
)
],
)),
));
});
});
}
#override
Widget build(BuildContext context) {
double listHeight = MediaQuery.of(context).size.height * 0.86;
double listWidth = MediaQuery.of(context).size.width * 0.97;
getData(context);
return ClipRRect(
borderRadius: BorderRadius.only(
topRight: Radius.circular(50), topLeft: Radius.circular(50)),
child: Container(
height: listHeight,
width: listWidth,
child: ListView.builder(
itemCount: itemData.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.only(bottom: 30),
child: itemData[index],
);
}),
));
}
}
``
Try using the Align widget. Just wrap the column with an align widget and have the alignment parameter be alignment.centerLeft.
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index){
return MaterialButton(
child: Align(
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello"),
],
),
alignment: Alignment.centerLeft,
)
);
}
),
);
}
}