invalid arguments from widget parameters? - android

I used two buttons which make same thing on subcategories screen. On of them in buttom of the screen, other one stays in subcategories part (Empty Card )of the screen, from the bottom button I can add new subcategory but when I pushed to the EmptyCard to add subcategory, adding screen is oppening but when I try to push add button, I took invalid argument(s) error, Can someone help me..
class CategoryModel{
CategoryModel({this.categoryId,this.categoryImagePath,this.categoryName,this.categoryColor,this.subCategory});
final int categoryId;
final SubCategoryModel subCategory;
final Color categoryColor;
final String categoryImagePath;
final String categoryName;
final List<SubCategoryModel> subCategoryModels=[SubCategoryModel(subCategoryId: null)];
}
class SubCategoryModel{
SubCategoryModel({this.subCategoryId,this.subCategoryImagePath,this.subCategoryName, this.categoryColor});
final int subCategoryId;
final Color categoryColor;
final subCategoryImagePath;
final subCategoryName;
class EmptyCard extends StatelessWidget {
EmptyCard({this.where});
final String where;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: TextButton(
onPressed: (){
if(where=="homeScreen"){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route:where),
);
}
else if(where=="subCategoryScreen"){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Tarif Ekle",route:where),
);
}
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.black12.withOpacity(0.1),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.add_circle_outline_outlined,size: 100,color: Colors.grey.shade400,),
],
),
),
),
);
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: BorderedText(
child:Text(
categoryModels[widget.categoryId].categoryName,
style: TextStyle(
color: Color(0XFFFFFB00),
fontSize: 30,
fontFamily: "Graduate"
),
),
strokeWidth: 5,
strokeColor: Colors.black,
),
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: (){
Navigator.pop(context);
},
iconSize: 40,
color: Color(0xFFA2000B),
),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage("images/cuttedlogo.PNG"),
)
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/logoBGopacity.png"),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.builder(
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount:categoryModels[widget.categoryId].subCategoryModels.length,
itemBuilder: (context,index){
if(categoryModels[widget.categoryId].subCategoryModels[index].subCategoryId==null){
return EmptyCard(where: "subCategoryScreen");
}
return SubCategoryCard(subCategoryId:widget.categoryId,subcategoryName: categoryModels[widget.categoryId].subCategoryModels[index].subCategoryName,
subCategoryImagePath: categoryModels[widget.categoryId].subCategoryModels[index].subCategoryImagePath,
subCategoryColor: categoryModels[widget.categoryId].subCategoryModels[index].categoryColor,);
}
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: TextButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(categoryId:widget.categoryId,buttonText: "Tarif Ekle", route:"subCategoryScreen"),
);
},
child: BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text("Tarif Ekle",style: TextStyle(
color: Colors.white,
fontFamily:'Graduate',
fontSize:30,
),
),
),
),
),
),
],
)
],
),
),
),
);
}
}
class AddMenuScreen extends StatefulWidget {
AddMenuScreen({this.categoryId,this.buttonText, this.route});
final int categoryId;
final String route;
final String buttonText;
static String id="addMenuScreen";
#override
_AddMenuScreenState createState() => _AddMenuScreenState();
}
class _AddMenuScreenState extends State<AddMenuScreen> {
final stickerList= List<String>.generate(23, (index) => "images/sticker$index");
int selectedIndex=-1;
Color _containerForStickersInactiveColor=Colors.white;
Color _containerForStickersActiveColor=Colors.black12;
String chosenImagePath;
String newCategoryName;
int addScreenImageNum;
#override
Widget build(BuildContext context) {
return Material(
child: Container(
color: kColorTheme9,
child: Container(
height: 400,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(40),topLeft: Radius.circular(40)),
),
child:Padding(
padding:EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color: kColorTheme2,
borderRadius: BorderRadius.circular(90)
),
child: TextField(
style: TextStyle(
color: Colors.black,
fontFamily:"Graduate",
fontSize: 20,
),
textAlign: TextAlign.center,
onChanged: (value){
newCategoryName=value;
},
decoration: InputDecoration(
border:OutlineInputBorder(
borderRadius: BorderRadius.circular(90),
borderSide: BorderSide(
color: Colors.teal,
),
),
hintText: "Menü ismi belirleyin",
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.2),
fontFamily: "Graduate",
),
),
),
),
SizedBox(height: 20,),
Text(" Yana kadırarak menünüz icin bir resim secin",textAlign: TextAlign.center,
style: TextStyle(fontFamily: "Graduate", fontSize: 12),),
SizedBox(height: 20,),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: stickerList.length,
itemBuilder: (context,index){
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: index == selectedIndex ?
_containerForStickersActiveColor :
_containerForStickersInactiveColor,
),
child:TextButton(
child: Image(
image: AssetImage("images/sticker$index.png"),
),
onPressed: (){
setState(() {
selectedIndex = index;
});
},
),
);
}
),
),
SizedBox(height: 20,),
Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(90),
),
child: TextButton(
onPressed: (){
if(widget.route=="homeScreen"){
Navigator.pop(context, ModalRoute.withName(HomeScreen.id));
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>HomeScreen(newCategoryName: newCategoryName,
newCategoryImagePath: "images/sticker$selectedIndex.png")));
}
else if(widget.route=="subCategoryScreen"){
Navigator.pop(context, ModalRoute.withName(SubCategoriesScreen.id));
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>SubCategoriesScreen(categoryId: widget.categoryId,subCategoryName: newCategoryName,
subCategoryImagePath:"images/sticker$selectedIndex.png" )));
}
},
child: Text(widget.buttonText, style: TextStyle(fontSize: 20, color: Colors.white,
fontFamily: "Graduate", fontWeight: FontWeight.bold),),
),
),
],
),
),
),
),
);
}
}

Related

Error: "I/Process ( 4121): Sending signal. PID: 4121 SIG: 9 Lost connection to device.." while using flutter on android studio

"Sending signal. PID: 4121 SIG: 9 Lost connection to device" I never seen that problem in my Android Studio IDE of my Computer. But When I was import this project on another computer and run in Emulator I saw that error .this is a ecommerce project. After the login Success the app will show Homepage. The Homepage Will show products from firebase. But the app exit.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:ecommercedemo/main.dart';
import 'package:ecommercedemo/screens/Cart.dart';
import 'package:ecommercedemo/screens/product_details_page.dart';
import 'package:ecommercedemo/screens/profile_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
class HomePage extends StatefulWidget {
//const HomePage({Key? key}) : super(key: key);
String? category;
HomePage(String category){
this.category=category;
}
#override
_HomePageState createState() => _HomePageState(category!);
}
class _HomePageState extends State<HomePage> {
String? category;
_HomePageState(String category){
this.category=category;
}
int m=0;
#override
Widget build(BuildContext context) {
final size=MediaQuery.of(context).size;
return Scaffold(
//backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.white,
title: Padding(
padding: const EdgeInsets.only(left: 0),
child: Container(
width: double.infinity,
height: 40,
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(5)),
child: Center(
child: TextField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
prefixIcon: Icon(Icons.search),
suffixIcon: IconButton(
icon: Icon(Icons.clear),
onPressed: () {
/* Clear the search field */
},
),
hintText: 'Search...',
border: InputBorder.none),
),
),
),
),
// actions: <Widget>[
// IconButton(icon: Icon(Icons.search),
// onPressed: () {
// //showSearch(context: context, delegate: DataSearch(listWords));
// })
// ],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Expanded(
flex: 30,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: Color(0xffffaf38),
borderRadius: BorderRadius.circular(15)
),
alignment: Alignment.center,
height: 100,
width: size.width,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.black,
shape: CircleBorder(),
//padding: EdgeInsets.all(30)
),
onPressed: (){
mode=1;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('Kids')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/kids.png"),
radius: 30,
),
),
Text("Kids")
],
),
Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder(),
//padding: EdgeInsets.all(30)
),
onPressed: (){
mode=2;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('Device')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/mensitem.png"),
radius: 30,
),
),
Text('Devices')
],
),
Column(
children: [
ElevatedButton(
onPressed: (){
mode=3;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('men')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/men's.png"),
radius: 30,
),
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder()
),
),
Text("Men's")
],
),
Column(
children: [
ElevatedButton(
onPressed: (){
mode=4;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage("Women")), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/girls.png"),
radius: 30,
),
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder()
),
),
Text("Women")
],
),
Column(
children: [
ElevatedButton(
onPressed: (){
mode=5;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('electronics')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/Devices.png"),
radius: 30,
),
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder()
),
),
Text("Electronics")
],
)
],
),
),
),
),
),
),
Expanded(
flex: 70,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: Color(0xffffaf38),
borderRadius: BorderRadius.circular(15)
),
alignment: Alignment.center,
height: size.height,
width: size.width,
child: _buildcondition(category!)
// Column(
// children: [
// _buildDefuListView()
// // if (mode == 0) ...[
// // _buildDefuListView()
// // ] else if (mode == 5) ...[
// // _buildListView(mode)
// // ]
// ],
// ),
),
),
),
],
),
),
drawer: Drawer(
child: ListView(
children: [
UserAccountsDrawerHeader(
accountName: Text("Gunjon Roy"),
accountEmail: Text("gunjon.cse#gmail.com"),
currentAccountPicture: CircleAvatar(
radius: 20,
backgroundImage: AssetImage("images/men's.png"),
child: Text("Edit"),
),
),
ListTile(
leading: Icon(Icons.shopping_cart),
title: Text("Carts"),
onTap: (){
print("hello world<<<<<<<<<<<<>>>>>>>>>>>>>>");
},
)
],
),
),
bottomNavigationBar: Container(
height: MediaQuery.of(context).size.height * 0.06,
color: Colors.white,
child: Row(
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.03,
),
FlatButton(
onPressed: () {},
child: Text(
'Explore',
style: TextStyle(color: Color(0xFFfca903)),
)),
SizedBox(
width: MediaQuery.of(context).size.width * 0.15,
),
FlatButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>Cart()));
},
child: Icon(
Icons.add_shopping_cart,
color: Color(0xFFfca903),
)),
SizedBox(
width: MediaQuery.of(context).size.width * 0.12,
),
FlatButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>Profile()));
},
child: Icon(
Icons.perm_identity_outlined,
color: Color(0xFFfca903),
)),
],
),
),
);
}
Widget _buildListView(String mode){
// String? who;
// if(number==5){
// who="kids";
// }else if(number==16){
// who="boys";
// }else if(number==18){
// who="mens";
// }else if(number==21){
// who="girls";
// }else{
// who="";
// }
//var item = '';
final size=MediaQuery.of(context).size;
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('product').document(mode).collection(mode).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: Column(
children: [
CircularProgressIndicator(),
Text('Loading...',style: TextStyle(color: Colors.white),),
],
));
} else
return SingleChildScrollView(
child: ListView(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: snapshot.data!.documents.map((document){
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color(0xFFff9f36)
),
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(
mode,
document['name'] ?? '',
document['details'] ?? '',
document['price'] ?? '',
document['imageUrl'] ?? ''
)));
},
child: ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//NetworkImage(),
Card(
elevation: 20,
color: Colors.white,
//BoxDecoration(color: Colors.black)
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
side:
BorderSide(color: Colors.black)),
child: Container(
height: MediaQuery.of(context).size.height * 0.35,
width: MediaQuery.of(context).size.width * 0.45,
child: Image(
image: NetworkImage(
document['imageUrl'] ?? '')),
),
),
Padding(
padding: const EdgeInsets.only(left: 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
document['name'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['details'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['price'] ?? '',
style: TextStyle(color: Colors.white),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.015,)
],
),
),
],
),
),
);
}).toList()),
);
}
);
// ListView.builder(
// scrollDirection: Axis.vertical,
// itemCount: number,
// itemBuilder: (BuildContext context, int index) {
// return Padding(
// padding: const EdgeInsets.only(bottom: 20),
// child: Container(
// decoration: BoxDecoration(
// color: Colors.grey,
// borderRadius: BorderRadius.circular(15)
// ),
// width: 50,
// height: 100,
// //child: SizedBox(width: 20,),
// ),
// );
// },
// );
}
Widget _buildDefuListView(var mode){
final size=MediaQuery.of(context).size;
return Column(
//crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Best Selling",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.white
),
),
SizedBox(width: size.width*.3,),
// ElevatedButton(
// style: ElevatedButton.styleFrom(
// primary: Colors.white
// ),
// onPressed: (){
//
// }, child: Text("See all",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// fontSize: 20,
// color: Colors.white
// ),
// )
// )
TextButton(
onPressed: (){
},
child: Text("See all",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white
),
)
),
],
),
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('product').document(mode).collection(mode).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: Column(
children: [
CircularProgressIndicator(),
Text('Loading...',style: TextStyle(color: Colors.white),),
],
));
} else
return SingleChildScrollView(
child: ListView(
physics: NeverScrollableScrollPhysics(),
//physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: snapshot.data!.documents.map((document){
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color(0xFFff9f36)
),
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(
mode,
document['name'] ?? '',
document['details'] ?? '',
document['price'] ?? '',
document['imageUrl'] ?? ''
)));
},
child: ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//NetworkImage(),
Card(
elevation: 20,
color: Colors.white,
//BoxDecoration(color: Colors.black)
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
side:
BorderSide(color: Colors.black)),
child: Container(
height: MediaQuery.of(context).size.height * 0.35,
width: MediaQuery.of(context).size.width * 0.45,
child: Image(
image: NetworkImage(
document['imageUrl'] ?? '')),
),
),
Padding(
padding: const EdgeInsets.only(left: 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
document['name'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['details'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['price'] ?? '',
style: TextStyle(color: Colors.white),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.015,)
],
),
),
],
),
),
);
}).toList()),
);
}
),
],
);
}
Widget _buildcondition(String mode){
if(mode=='women'){
return _buildListView(mode);
}
else if(mode=='men'){
return _buildListView(mode);
}
else if(mode=='Device'){
return _buildListView(mode);
}
else if(mode=='Kids'){
return _buildListView(mode);
}
else if(mode=='electronics'){
return _buildListView(mode);
}
else{
return _buildListView('women');
//_buildListView('women');
}
}
}

flutter text field value from API resetting on keyboard close

I have implemented BLOC architecture for a user profile edit for a logged in user in flutter. The inputs are filled with user's existing info which I got from the API. But whenever input is focused and keyboard closes the entered value gets replaced with the initial value which I got from the API response.
This is my View profile UI
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:payd/services/profile_service.dart';
import 'package:payd/bloc/profile_bloc.dart';
import 'package:payd/model/profile_model.dart';
void main() {
runApp(EditProfile());
}
class EditProfile extends StatefulWidget {
#override
_EditProfilesState createState() => _EditProfilesState();
}
class _EditProfilesState extends State<EditProfile>
with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Image.asset('assets/logo.png', fit: BoxFit.cover),
actions: [
IconButton(
onPressed: () {},
icon: Image.asset('assets/Icon feather-bell.png'),
iconSize: 30,
),
],
elevation: 5,
),
backgroundColor: Color(0xFF33138C),
body: BlocProvider(
create: (context) => ProfileBloc(ProfileService()),
child: Body(),
),
);
}
#override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}
class Body extends StatelessWidget {
static final _formKey = GlobalKey<FormState>();
void _submit() {
final isValid = _formKey.currentState.validate();
if (!isValid) {
return;
}
_formKey.currentState.save();
}
#override
Widget build(BuildContext context) {
final textFieldFocusNode = FocusNode();
final profileBloc = BlocProvider.of<ProfileBloc>(context);
var userSlug = '52q6x93k4y';
profileBloc.add(FetchProfile(userSlug));
Size size = MediaQuery.of(context).size;
return Container(
constraints: BoxConstraints.expand(),
decoration: BoxDecoration(
image: DecorationImage(
image: new ExactAssetImage('assets/app-background.png'),
fit: BoxFit.cover)),
child: Padding(
padding: const EdgeInsets.all(0),
child: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Column(
children: <Widget>[
SizedBox(
height: size.height,
child: Stack(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: size.height * 0.04),
// height: 400,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40.0),
topRight: Radius.circular(40.0),
),
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Column(
children: [
Container(
padding: EdgeInsets.only(
top: 30.0,
left: 20.0, bottom: 25.0),
alignment: Alignment.centerLeft,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.keyboard_arrow_left),
iconSize: 30,
),
),
],
),
Column(
children: [
Container(
padding: EdgeInsets.only(
top: 30.0,
right: 30.0, bottom: 25.0),
alignment: Alignment.centerLeft,
child: Text(
'Edit Account',
style: const TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.w600,
color: Colors.black54),
),
),
],
),
],
),
BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
print(state);
if (state is ProfileIsLoaded) {
return Container(
child: Flexible(
child: SingleChildScrollView(
reverse: true,
padding:
EdgeInsets.only(left: 16, right: 16),
child: Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(
bottom:
size.height > 700
? 20
: 15),
padding: EdgeInsets.only(
left: 20.0,
right: 20.0,
bottom: 25.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
controller: TextEditingController(
text: state.getProfile.firstName),
decoration: InputDecoration(
labelText: 'First Name'),
keyboardType: TextInputType
.name,
onFieldSubmitted: (
value) {
//Validator
},
validator: (value) {
if (value.isEmpty) {
return 'Required';
}
return null;
},
),
//box styling
SizedBox(
height: MediaQuery
.of(context)
.size
.width *
0.1,
),
TextFormField(
controller: TextEditingController(
text: state.getProfile.lastName),
decoration: InputDecoration(
labelText: 'Last Name'),
keyboardType: TextInputType
.name,
onFieldSubmitted: (
value) {
//Validator
},
validator: (value) {
if (value.isEmpty) {
return 'Required';
}
return null;
},
),
//box styling
SizedBox(
height: MediaQuery
.of(context)
.size
.width *
0.1,
),
SizedBox(
width: double.infinity,
child: TextButton(
style: ButtonStyle(
padding: MaterialStateProperty
.all(
EdgeInsets.only(
top: 16.0,
bottom: 16.0),),
foregroundColor:
MaterialStateProperty
.all<Color>(
Colors.white),
backgroundColor: MaterialStateProperty
.all<Color>(
Color(
0xFF33138C)),
shape: MaterialStateProperty
.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius
.circular(
25.0),
side: BorderSide(
color: Color(
0xFF33138C)))),),
onPressed: () =>
_submit(),
child: Text('Save',
style: TextStyle(
fontSize: 16.0
),),
),
),
],
),
),
),
],
),
),
),
);
} else {
return Center(child : CircularProgressIndicator());
}
}
),
SizedBox(height: 150),
],
)),
],
))
],
),
),
),
);
}
}
class ProfileError extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[Image.asset('assets/empty-list.png')],
),
Text(
'Error',
style: const TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w600,
color: Colors.black87),
),
Padding(
padding: EdgeInsets.only(left: 30.0, right: 30.0),
child: Text(
'After your first order you\'ll be able to view it here',
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.w600,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
),
],
),
);
}
}

How to share data between two widgets by using Provider?

I have two widgets which I shared codes below, In first card widget for user selecting ingredients, second card will be used for displaying selected ingrediens, initial both screen will be empty, when user add an igredients both widget will be rebuilt by according to selected ingredients, I could handle it displaying in first widget, but I can not handle to display selectedIngredient list data when it changes, I know I have to use provider packages but I could not implement for my code, I have stuck please help me.. .
class AddIngredientsCard extends StatefulWidget {
AddIngredientsCard({this.subCategoryId,this.subCategoryCardId});
final int subCategoryCardId;
final int subCategoryId;
#override
_AddIngredientsCardState createState() => _AddIngredientsCardState();
}
class _AddIngredientsCardState extends State<AddIngredientsCard>{
String textValue;
double _animatedContainerHeight=350;
double _top=15;
double _right=30;
double _left=30;
double _bottom=15;
List<String> items= [];
List<String>selectedIngredients=[];
#override
void initState() {
ingredients=ingredients..sort((String a, String b)=>a.compareTo(b));
items.addAll(ingredients);
super.initState();
}
void filterSearchResults(String query) {
List<String> searchList = [];
searchList.addAll(ingredients);
if(query.isNotEmpty) {
List<String> listData = [];
searchList.forEach((item) {
if(item.contains(query)) {
listData.add(item);
}
});
setState(() {
items.clear();
items.addAll(listData);
});
return;
} else {
setState(() {
items.clear();
items.addAll(ingredients);
});
}
}
void _toggleCardSize(){
_top==15?_top=7.5: _top=15;
_right==30?_right=7.5: _right=30;
_left==30?_left=7.5: _left=30;
_bottom==15?_bottom=7.5: _bottom=15;
}
void _toggleCardHeight(){
_animatedContainerHeight==350?_animatedContainerHeight=600:_animatedContainerHeight=350;
}
#override
Widget build(BuildContext context) {
return AnimatedPadding(
duration: Duration(milliseconds: 500),
curve: Curves.linearToEaseOut,
padding:EdgeInsets.only(top: _top,right: _right,left: _left,bottom: _bottom),
child: AnimatedContainer(
height:_animatedContainerHeight,
duration: Duration(milliseconds: 500),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
border:Border.all(style: BorderStyle.solid, width: 1),
color: Colors.white,
borderRadius: BorderRadius.circular(90),
),
height: 60,
child: TextField(
style: TextStyle(
color: Colors.black,
fontFamily:"OpenSans",
fontSize: 20,
),
textAlign: TextAlign.center,
textAlignVertical: TextAlignVertical.center,
onChanged: (value){
if(value.length>0){
value=value[0].toUpperCase()+value.substring(1);
filterSearchResults(value);
}
else{
filterSearchResults(value);
}
},
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
border:OutlineInputBorder(
borderRadius: BorderRadius.circular(90),
borderSide: BorderSide(
color: kColorTheme10,
),
),
hintText: "Malzeme ismi arayın",
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.5),
fontFamily: "OpenSans",
),
),
),
),
SizedBox(height: 2,),
Expanded(
flex: _animatedContainerHeight==350?1:4,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: selectedIngredients.length,
itemBuilder: (context,index){
return Padding(
padding: EdgeInsets.all(1),
child: GestureDetector(
onTap: (){
setState(() {
selectedIngredients.removeAt(index);
if (selectedIngredients.length == 0) {
_toggleCardHeight();
_toggleCardSize();
}
}
);
},
child: Container(
decoration: BoxDecoration(
color: kColorTheme11,
borderRadius: BorderRadius.circular(90),
border: Border.all(style: BorderStyle.solid,width: 1),
),
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
BorderedText(strokeColor: Colors.black,strokeWidth: 5,child: Text(selectedIngredients[index],style:
TextStyle(fontWeight: FontWeight.bold,fontSize:20,color: Colors.white),)),
SizedBox(width: 5,),
Icon(
Icons.cancel,color: Colors.white,size: 20,
),
],
),
),
),
),
);
}
),
),
SizedBox(height: 2,),
Expanded(
flex: 40,
child: ListView.builder(
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.all(2.0),
child: GestureDetector(
onTap: (){
setState(() {
if(selectedIngredients.length==0){
selectedIngredients.add("${items[index]}");
_toggleCardHeight();
_toggleCardSize();
}
else{
selectedIngredients.add("${items[index]}");
}
});
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(90),
border: Border.all(style:BorderStyle.solid,width: 1),
color: Colors.white54,
),
child: Padding(
padding: EdgeInsets.all(5),
child: Text('${items[index]}',style: TextStyle(fontWeight: FontWeight.bold),)),
),
),
);
},
),
),
SizedBox(height: 8,),
Expanded(
flex: _animatedContainerHeight==350?1:4,
child: Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
color: _animatedContainerHeight==350?categoryModels[widget.subCategoryId].
subCategoryModels[widget.subCategoryCardId].categoryColor.withOpacity(0.1):kColorTheme11,
borderRadius: BorderRadius.circular(20),
border: _animatedContainerHeight==350?null:
Border.all(style: BorderStyle.solid,width: 2),
),
child: Padding(
padding: EdgeInsets.all(5),
child: GestureDetector(
onTap: (){
AddIngredientsAmount(subCategoryId:widget.subCategoryId,subCategoryCardId: widget.subCategoryId,selectedIngredients: selectedIngredients,);
/////////////////////////////////////// => isPageSaved için Provider eklenecek...
},
child: Center(child: BorderedText(strokeWidth:3,strokeColor: Colors.black,child:
Text("KAYDET",style: TextStyle(fontSize: 25, fontWeight: FontWeight.w900 ,color: Colors.white))),
),
),
),
)
),
],
),
),
],
),
),
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid, width: 1),
borderRadius: BorderRadius.circular(30),
color:categoryModels[widget.subCategoryId].subCategoryModels[widget.subCategoryCardId].categoryColor.withOpacity(0.5),
)
),
);
}
}
class AddIngredientsAmount extends StatefulWidget {
AddIngredientsAmount({this.subCategoryId,this.subCategoryCardId, this.selectedIngredients});
final List selectedIngredients;
final int subCategoryCardId;
final int subCategoryId;
#override
_AddIngredientsAmountState createState() => _AddIngredientsAmountState();
}
class _AddIngredientsAmountState extends State<AddIngredientsAmount> {
String textValue;
double _animatedContainerHeight=300;
double _top=15;
double _right=30;
double _left=30;
double _bottom=15;
#override
Widget build(BuildContext context) {
void _toggleCardSize(){
_top==15?_top=7.5: _top=15;
_right==30?_right=7.5: _right=30;
_left==30?_left=7.5: _left=30;
_bottom==15?_bottom=7.5: _bottom=15;
}
void _toggleCardHeight(){
_animatedContainerHeight==300?_animatedContainerHeight=500:_animatedContainerHeight=300;
}
return AnimatedPadding(
duration: Duration(milliseconds: 500),
curve: Curves.linearToEaseOut,
padding:EdgeInsets.only(top: _top,right: _right,left: _left,bottom: _bottom),
child: GestureDetector(
onTap: (){
setState(() {
_toggleCardHeight();
_toggleCardSize();
});
},
child: AnimatedContainer(
height:_animatedContainerHeight,
duration: Duration(milliseconds: 500),
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
decoration: BoxDecoration(
border:Border.all(style: BorderStyle.solid, width: 1),
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(90))),
child: Center(
child: Text("Malzemelerinizin Miktarını Belirlerin",style: TextStyle(
color: Colors.black,
fontFamily:'OpenSans',
fontSize:25,
fontWeight: FontWeight.w300,
),
),
),
),
SizedBox(height: 7.5,),
Expanded(
child: Container(
decoration: BoxDecoration(
color:Colors.white,
border: Border.all(style: BorderStyle.solid, width: 1),
borderRadius: BorderRadius.circular(10),
),
child: ListView.builder(
itemCount: widget.selectedIngredients.length==null?0:
widget.selectedIngredients.length,
itemBuilder: (context, index){
return Padding(
padding: EdgeInsets.all(2),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(90),
border: Border.all(style:BorderStyle.solid,width: 1),
color: Colors.white54,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(5),
child: Text('${widget.selectedIngredients[index]}',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 30),)),
],
),
),
);
},
),
),
),
],
),
),
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid, width: 1),
borderRadius: BorderRadius.circular(30),
color:categoryModels[widget.subCategoryId].subCategoryModels[widget.subCategoryCardId].categoryColor.withOpacity(0.5),
)
)
),
);
}
}
//------------------------------------------------------------------------
class AddRecipeVoice extends StatefulWidget {
AddRecipeVoice({this.subCategoryId,this.subCategoryCardId});
final int subCategoryCardId;
final int subCategoryId;
#override
_AddRecipeVoiceState createState() => _AddRecipeVoiceState();
}
class _AddRecipeVoiceState extends State<AddRecipeVoice> {
String textValue;
#override
Widget build(BuildContext context) {
return AnimatedPadding(
duration: Duration(seconds: 1),
curve: Curves.linearToEaseOut,
padding:EdgeInsets.only(top: 15,left: 30,right: 30,bottom: 7.5),
child: GestureDetector(
onTap: (){
setState(() {
});
},
child: Container(
height:130,
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
decoration: BoxDecoration(
border:Border.all(style: BorderStyle.solid, width: 1),
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(90))),
child: Center(
child: Text("Tarifinizi anlatın",style: TextStyle(
color: Colors.black,
fontFamily:'OpenSans',
fontSize:25,
fontWeight: FontWeight.w300,
),
),
),
),
SizedBox(height: 7.5,),
Expanded(
child: GestureDetector(
child: Container(
decoration: BoxDecoration(
color:kColorTheme7,
border: Border.all(style: BorderStyle.solid, width: 1),
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Icon(Icons.mic,size: 40,color: Colors.white,),
SizedBox(width: 50,),
Text(
"KAYIT ZAMANI !!",
style: TextStyle(
fontSize: 30,
fontFamily: "OpenSans",
color: Colors.white,
fontWeight: FontWeight.bold
),
),
],
),
),
),
),
],
),
),
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid, width: 1),
borderRadius: BorderRadius.circular(30),
color:categoryModels[widget.subCategoryId].subCategoryModels[widget.subCategoryCardId].categoryColor.withOpacity(0.5),
)
)
),
);
}
}
Make a provider class that mixin with ChangeNotifier.
Wrap your widget prior calling the provider class with MultiProvider widget. Likewise:
MultiProvider (
providers: [
ChangeNotifierProvider.value(value: IngredientsProvider()),
],
child: YourWidget(), //You can wrap your MaterialApp here
)
Create your needed methods that changes the selected data and call notifyListeners() inside your method. It will rebuild your desired widget where you listen to them.
Example:
class IngredientsProvider with ChangeNotifier {
List<String> _selectedIngredients = [];
List<String> get selectedIngredients() {
return _selectedIngredients;
}
void addIngredient(String ingredient) {
_selectedIngredients.add(ingredient);
notifyListeners();
}
}
In your widget listen to them:
Widget1 {
//Call this in you onPress/onTap
void addIngredient(String ing, BuildContext ctx) {
Provider.of<IngredientsProvider>(ctx, listen:
false).addIngredient(ing);
}
........
#override
Widget build(BuildContext context) {
//Use this list to select
List<String> _ingredients = Provider.of<IngredientsProvider>(context, listen:
true).ingredients;
}
........
}
Use in the 2nd Widget in this way.
Widget2 {
........
#override
Widget build(BuildContext context) {
//Use this list to show
List<String> _ingredients = Provider.of<IngredientsProvider>(context, listen:
true).ingredients;
}
........
}

How to show a Count down Timer within and Alertbox in flutter

i have a Flutter app which should show a counting down timer in an alert box for Phone code confirming (i need this timer to resend the code to my user when 60 second is up) , i start timer when i click on Confirm Button , but the problem is that the timer is not showing that he's going down he stills with a fixed value.
here is my alert box
Alert Box with timer NOT SHOWING COUNT DOWN
here is my timer Function :
int _counter = 60;
Timer _timer;
void _startTimer(){
_counter = 60;
if(_timer != null){
_timer.cancel();
}
_timer = Timer.periodic(Duration(seconds: 1), (timer){
setState(() {
(_counter > 0) ? _counter-- : _timer.cancel();
});
});
}
here is my alert Box code :
void alertD(BuildContext ctx) {
var alert = AlertDialog(
// title: Center(child:Text('Enter Code')),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
backgroundColor: Colors.grey[100],
elevation: 0.0,
content: Container(
height: 215,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: 10, left: 10, right: 10, bottom: 15),
child: Text(
'Enter Code',
style: TextStyle(
color: Colors.green[800],
fontWeight: FontWeight.bold,
fontSize: 16
),
)),
Container(
height: 70,
width: 180,
child: TextFormField(
style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.green, width: 0.0)),
),
keyboardType: TextInputType.number,
maxLength: 10,
),
),
SizedBox(
height: 1,
),
Text('00:$_counter'),
SizedBox(height: 15,)
,
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Material(
child: InkWell(
onTap: () {
Navigator.of(ctx).pushNamed(SignUpScreenSecond.routeName);
},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
gradient: LinearGradient(
colors: [
Colors.green,
Colors.grey,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Center(
child: Text(
'Validate',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
)),
),
),
),
),
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Material(
child: InkWell(
onTap: () {},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
gradient: LinearGradient(
colors: [
Colors.grey,
Colors.green,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Center(
child: Text(
'Resend',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
)),
),
),
),
)
],
), //new column child
],
),
));
showDialog(
context: ctx,
builder: (BuildContext c) {
return alert;
});
}
that's how i'm calling my alert dialog and my timer when i click Confirm Button :
onTap: () {
_startTimer;
alertD(context);
},
You can copy paste run full code below
You can use StreamBuilder and StreamController
AlertDialog content continually receive stream int from Timer
code snippet
StreamController<int> _events;
#override
initState() {
super.initState();
_events = new StreamController<int>();
_events.add(60);
}
...
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
(_counter > 0) ? _counter-- : _timer.cancel();
print(_counter);
_events.add(_counter);
});
...
content: StreamBuilder<int>(
stream: _events.stream,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
...
Text('00:${snapshot.data.toString()}'),
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
StreamController<int> _events;
#override
initState() {
super.initState();
_events = new StreamController<int>();
_events.add(60);
}
Timer _timer;
void _startTimer() {
_counter = 60;
if (_timer != null) {
_timer.cancel();
}
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
//setState(() {
(_counter > 0) ? _counter-- : _timer.cancel();
//});
print(_counter);
_events.add(_counter);
});
}
void alertD(BuildContext ctx) {
var alert = AlertDialog(
// title: Center(child:Text('Enter Code')),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
backgroundColor: Colors.grey[100],
elevation: 0.0,
content: StreamBuilder<int>(
stream: _events.stream,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
print(snapshot.data.toString());
return Container(
height: 215,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: 10, left: 10, right: 10, bottom: 15),
child: Text(
'Enter Code',
style: TextStyle(
color: Colors.green[800],
fontWeight: FontWeight.bold,
fontSize: 16),
)),
Container(
height: 70,
width: 180,
child: TextFormField(
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.green, width: 0.0)),
),
keyboardType: TextInputType.number,
maxLength: 10,
),
),
SizedBox(
height: 1,
),
Text('00:${snapshot.data.toString()}'),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Material(
child: InkWell(
onTap: () {
//Navigator.of(ctx).pushNamed(SignUpScreenSecond.routeName);
},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
gradient: LinearGradient(
colors: [
Colors.green,
Colors.grey,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Center(
child: Text(
'Validate',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
)),
),
),
),
),
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Material(
child: InkWell(
onTap: () {},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
gradient: LinearGradient(
colors: [
Colors.grey,
Colors.green,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Center(
child: Text(
'Resend',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
)),
),
),
),
)
],
), //new column child
],
),
);
}));
showDialog(
context: ctx,
builder: (BuildContext c) {
return alert;
});
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
_startTimer();
alertD(context);
},
child: Text('Click')),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Screen is not closing on click on press of alert dialog in flutter

Hi I have designed a screen in flutter. I have AlertDialog on which I want to close the dialog and screen on pressing. Right now AlertDialog dismiss on press but screen is not closing.
Does anyone know how to do this ?
class ForgotPasswordScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return ForgotPasswordScreenState();
}
}
class ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
var emailController = new TextEditingController();
var authHandler = new Auth();
bool isLoading = false;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
color: Colors.white,
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Row(
children: <Widget>[
new Expanded(
child: isLoading
? Center(child: CircularProgressIndicator())
: new Container()),
],
),
new Row(
children: <Widget>[
new Expanded(
child: new Padding(
padding: const EdgeInsets.only(left: 40.0),
child: new Text(
"EMAIL",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.redAccent,
fontSize: 15.0,
),
),
),
),
],
),
new Container(
width: MediaQuery.of(context).size.width,
margin:
const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.redAccent,
width: 0.5,
style: BorderStyle.solid),
),
),
padding: const EdgeInsets.only(left: 0.0, right: 10.0),
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Expanded(
child: TextField(
controller: emailController,
textAlign: TextAlign.left,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'PLEASE ENTER YOUR EMAIL',
hintStyle: TextStyle(color: Colors.grey),
),
),
),
],
),
),
Divider(
height: 24.0,
),
new Container(
width: MediaQuery.of(context).size.width,
margin:
const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
alignment: Alignment.center,
child: new Row(
children: <Widget>[
new Expanded(
child: new FlatButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
color: Colors.redAccent,
onPressed: () {
setState(() {
isLoading = true;
});
authHandler
.sendPasswordResetEmail(emailController.text)
.then((void nothing) {
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
content: new Text(
"Password reset email has been sent."),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
setState(() {
isLoading = false;
});
}).catchError((e) => print(e));
},
child: new Container(
padding: const EdgeInsets.symmetric(
vertical: 20.0,
horizontal: 20.0,
),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Expanded(
child: Text(
"FORGOT PASSWORD",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
),
],
),
),
],
)));
}
}
Ideally, you'll want to call pop more than once. One for the modal, another for the actual route.
There are a few ways to achieve this. But ideally you'll want to await the close of the dialog before triggering another close:
foo() async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
actions: [
new FlatButton(
child: new Text("OK"),
onPressed: () => Navigator.pop(context),
),
],
),
);
Navigator.pop(context);
}
This way, both the route and the modal can handle their close however they like.
This is how i did with mine
bool _logout = false;
and then at the start of build Widget
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
_onBackPressed(context);
return _logout;
},
child: Container(),
);
}
and the method _onBackPressed returns a custom dialog Class like so
void _onBackPressed(BuildContext c) async {
await showDialog(
barrierColor: CustomColors.darkGrey.withOpacity(0.8),
barrierDismissible: true,
context: context,
builder: (BuildContext context) {
return CustomDialogBox(
title: 'Logout',
description: 'Are you sure you want to logout?',
rightButtonText: 'Yes',
onPClick: () {
_logout = true;
if (_logout == true) {
Get.back();
}
},
onNClick: () {
_logout = false;
Get.back();
},
);
});
if (_logout == true) {
Get.back();
}
}
and my custom Dialog class is here
class CustomDialogBox extends StatefulWidget {
final String? title, description, leftButtonText, rightButtonText;
final VoidCallback? onPClick, onNClick;
final Image? image;
const CustomDialogBox({
Key? key,
this.title,
this.description,
this.leftButtonText,
this.rightButtonText,
this.image,
this.onPClick,
this.onNClick,
}) : super(key: key);
#override
_CustomDialogBoxState createState() =>
// ignore: no_logic_in_create_state
_CustomDialogBoxState(onPClick!, onNClick!);
}
class _CustomDialogBoxState extends State<CustomDialogBox> {
final VoidCallback onPClick, onNClick;
_CustomDialogBoxState(this.onPClick, this.onNClick);
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(Dimensions.BORDER_RADIUS_4),
),
elevation: 0,
backgroundColor: Colors.transparent,
child: Container(
//height: 200,
padding: const EdgeInsets.only(
left: 10,
right: 0,
bottom: 10,
),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: CustomColors.darkGrey,
offset: const Offset(0, 30),
blurRadius: 20,
),
]),
child: Wrap(children: <Widget>[
dialogBody(context),
]),
),
);
}
Widget dialogBody(context) {
return Column(children: [
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Image.asset(
Images.LOGO,
height: MediaQuery.of(context).size.height * 0.035,
),
IconButton(
//padding: const EdgeInsets.all(0),
onPressed: () {
Get.back();
},
icon: const CircleAvatar(
radius: 12.5,
child: Icon(
Icons.close,
color: Colors.white,
),
backgroundColor: Colors.red,
),
),
]),
Padding(
padding: const EdgeInsets.only(
right: 10,
),
child: Column(children: [
//----//
customText(
text: widget.title ?? '',
fontFamily: 'black',
fontSize: 16,
),
//----//
const Space(0, 0.01),
//----//
customText(
text: widget.description ?? '',
fontSize: 14,
),
]),
),
//----//
const Space(0, 0.03),
//----//
Padding(
padding: const EdgeInsets.only(
right: 10,
),
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
//----//
raisedButton(
text: widget.leftButtonText ?? 'Cancel',
fontFamily: 'roman',
height: 35,
width: 105,
buttonColor: CustomColors.red,
onClick: () {
return onNClick();
},
context: context,
),
//----//
raisedButton(
text: widget.rightButtonText ?? 'Okay',
fontFamily: 'roman',
height: 35,
width: 105,
buttonColor: CustomColors.green,
onClick: () {
return onPClick();
},
context: context,
),
//----//
]),
),
]);
}
}
the buttons and texts are custom so feel free to change them. and where you see Get.back(); is GetX code.. you can replace with Navigator.of(context).pop();
try this
showPop() async {
await showDialog(
context: context,
barrierDismissible: true,
builder: (context) => AlertDialog(
actions: [
new FlatButton(
child: new Text("Close"),
onPressed: () => Navigator.pop(context),
),
],
),
);
}

Categories

Resources