I am trying to create a web application using flutter and I have a question. After I go through authorization, I need to change the "login" button in the navbar, as I understand it, I need to change the button text and call setState in my navbar, but in my implementation an exception is thrown.
AuthPage.dart
import 'package:flutter/material.dart';
import 'package:um/pages/home/app_color.dart';
import 'package:um/scripts/api_client.dart';
import 'package:um/scripts/locator.dart';
import 'NavBarDesktop.dart';
class AuthorizationPageDesktop extends StatefulWidget {
AuthorizationPageDesktop({Key key}) : super(key: key);
#override
_AuthorizationPageDesktopState createState() =>
_AuthorizationPageDesktopState();
}
class _AuthorizationPageDesktopState extends State<AuthorizationPageDesktop> {
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
bool rememberMe = false;
ApiClient apiClient = ApiClient.getInstance();
ScrollController _scrollController = ScrollController();
PageController _pageController = PageController();
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
child: Padding(
padding: EdgeInsets.only(top: 150, left: 0, right: 0),
child: Column(
children: <Widget>[
Text(
'Авторизация',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 28,
color: textPrimaryColor),
),
SizedBox(
height: 40,
),
_input(Icon(Icons.mail), 'Email', _emailController, false, 15),
SizedBox(
height: 15,
),
_input(Icon(Icons.lock), 'Password', _passwordController, true, 15),
SizedBox(
height: 5,
),
Container(
padding: EdgeInsets.only(left: 20, right: 20),
width: 460,
child: Theme(
data: ThemeData(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
hoverColor: Colors.transparent),
child: CheckboxListTile(
title: Text(
'Запомнить меня',
style: TextStyle(color: textPrimaryColor),
),
value: rememberMe,
onChanged: (bool value) {
setState(() {
rememberMe = value;
});
},
))),
SizedBox(
height: 5,
),
_button('Войти', auth, 15),
SizedBox(
height: 15,
),
Container(
width: 460,
child: Align(
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Пройдите ',
style: TextStyle(color: Colors.white, fontSize: 12),
),
Text(
'регистрацию, ',
style: TextStyle(color: linkColor, fontSize: 12),
),
Text(
'если вы этого еще не сделали',
style: TextStyle(color: Colors.white, fontSize: 12),
),
],
)),
),
SizedBox(height: 50),
],
),
)));
}
Widget _input(Icon icon, String hint, TextEditingController controller,
bool obscure, double borderRadius) {
return Container(
width: 460,
height: 50,
padding: EdgeInsets.only(left: 20, right: 20),
child: TextField(
controller: controller,
obscureText: obscure,
style: TextStyle(fontSize: 16, color: Colors.white),
decoration: InputDecoration(
border: OutlineInputBorder(),
isDense: true, // Added this
contentPadding: EdgeInsets.all(8), //
hintStyle: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
hintText: hint,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(borderRadius),
borderSide: BorderSide(color: Colors.white, width: 2)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(borderRadius),
borderSide: BorderSide(color: Colors.white54, width: 1)),
prefixIcon: Padding(
padding: EdgeInsets.only(left: 10, right: 10),
child: IconTheme(
data: IconThemeData(color: Colors.white),
child: icon,
),
)),
),
);
}
Widget _button(String label, void func(), double borderRadius) {
return Container(
width: 460,
padding: EdgeInsets.only(left: 20, right: 20),
child: RaisedButton(
onPressed: () {
apiClient
.authorization(_emailController.text, _passwordController.text)
.then((value) {
func();
});
},
highlightColor: Theme.of(context).primaryColor,
color: buttonPrimaryColor,
child: Text('Войти',
style: TextStyle(
fontWeight: FontWeight.bold,
color: textPrimaryColor,
fontSize: 16)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRadius)),
));
}
void auth() {
var state = navBar<NavBarDesktop>().navBarState;
state.update();
}
}
NavBar.dart
import 'package:flutter/material.dart';
import 'package:um/Widgets/Desktop/AuthPageDesktop.dart';
import 'package:um/Widgets/Desktop/HomePageDesktop.dart';
import 'package:um/Widgets/NavBarItem.dart';
import 'package:um/layout_template/layout_template.dart';
import 'package:um/pages/home/app_color.dart';
import 'package:um/scripts/api_client.dart';
import 'package:um/scripts/locator.dart';
class NavBarDesktop extends StatefulWidget {
NavBarDesktop({Key key}) : super(key: key);
GlobalKey<_NavBarDesktopState> navBarDesktop =
GlobalKey<_NavBarDesktopState>();
_NavBarDesktopState navBarState = new _NavBarDesktopState();
static _NavBarDesktopState of(BuildContext context) {
// print('_NavBarDesktopState -> ${context}');
assert(context != null);
final _NavBarDesktopState result =
// ignore: deprecated_member_use
context.ancestorStateOfType(const TypeMatcher<_NavBarDesktopState>());
// print('_NavBarDesktopState resutl -> ${result}');
return result;
}
#override
_NavBarDesktopState createState() => new _NavBarDesktopState();
}
class _NavBarDesktopState extends State<NavBarDesktop> {
String authButtonTitle = "Войти";
#override
void initState() {
print('call init state navbar ${ApiClient.username}');
if (ApiClient.username != null && ApiClient.username.length > 0)
authButtonTitle = ApiClient.username;
super.initState();
}
void update() {
setState(() {
authButtonTitle = ApiClient.username;
});
}
#override
Widget build(BuildContext context) {
return new Container(
color: primaryColor,
height: 50,
padding: EdgeInsets.only(left: 50, right: 50),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
LayoutTemplate.of(context).change_page(HomePageDesktop());
},
child: Text(
'UM',
textAlign: TextAlign.center,
style: TextStyle(
color: textPrimaryColor,
fontWeight: FontWeight.w600,
fontSize: 40),
)),
NavBarItem(
authButtonTitle,
() => LayoutTemplate.of(context)
.change_page(AuthorizationPageDesktop())),
],
),
);
}
void auth_page_up(BuildContext context) {
LayoutTemplate.of(context).change_page(AuthorizationPageDesktop());
}
}
Exception
Error: setState() called in constructor: _NavBarDesktopState#5e1ee(lifecycle state: created, no widget, not mounted)
This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to
call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.
at Object.throw_ [as throw] (http://localhost:50572/dart_sdk.js:4334:11)
at http://localhost:50572/packages/flutter/src/widgets/widget_span.dart.lib.js:13615:23
at NavBarDesktop._NavBarDesktopState.new.setState (http://localhost:50572/packages/flutter/src/widgets/widget_span.dart.lib.js:13618:26)
at NavBarDesktop._NavBarDesktopState.new.update (http://localhost:50572/packages/um/scripts/router.dart.lib.js:1717:12)
at AuthPageDesktop._AuthorizationPageDesktopState.new.auth (http://localhost:50572/packages/um/scripts/router.dart.lib.js:1932:13)
at http://localhost:50572/packages/um/scripts/router.dart.lib.js:1926:15
at _RootZone.runUnary (http://localhost:50572/dart_sdk.js:37457:58)
at _FutureListener.then.handleValue (http://localhost:50572/dart_sdk.js:32441:29)
at handleValueCallback (http://localhost:50572/dart_sdk.js:32988:49)
at Function._propagateToListeners (http://localhost:50572/dart_sdk.js:33026:17)
at _Future.new.[_completeWithValue] (http://localhost:50572/dart_sdk.js:32869:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:50572/dart_sdk.js:32891:35)
at Object._microtaskLoop (http://localhost:50572/dart_sdk.js:37718:13)
at _startMicrotaskLoop (http://localhost:50572/dart_sdk.js:37724:13)
at http://localhost:50572/dart_sdk.js:33243:9
Your _NavBarDesktopState global key needs to be initialized in your _NavBarDesktopState class., not the NavBarDesktop class. It's trying to set the global key before the state has even been created.
class NavBarDesktop extends StatefulWidget {
NavBarDesktop({Key key}) : super(key: key);
_NavBarDesktopState navBarState;
static _NavBarDesktopState of(BuildContext context) {
assert(context != null);
final _NavBarDesktopState result =
// ignore: deprecated_member_use
context.ancestorStateOfType(const TypeMatcher<_NavBarDesktopState>());
return result;
}
#override
_NavBarDesktopState createState() {
navBar.registerLazySingleton(() => this);
navBarState = _NavBarDesktopState();
return navBarState;
}
}
Related
I'm working on a big company project and a screen needed search bar but it works ok when you type one Letter or two but then if you continue to type in search it shows the whole names in it how do i fix this i want the list to show nothing when search term is wrong
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:reports/core/locale/locale_helper.dart';
import 'package:reports/core/util/constants.dart';
import 'package:reports/core/util/my_icons.dart';
import 'package:reports/core/util/responsive.dart';
import 'package:reports/features/reports/presentation/widgets/report_app_bar.dart';
import '../../../../../core/util/my_colors.dart';
class Marketer extends Equatable {
Marketer({
required this.name,
required this.code,
});
late String name;
final int code;
#override
List<Object?> get props => [code];
}
class Marketerselect extends StatefulWidget {
Marketer? selectedValue;
Marketerselect({
Key? key,
this.selectedValue,
}) : super(key: key);
#override
State<Marketerselect> createState() => _MarketerselectState();
}
class _MarketerselectState extends State<Marketerselect> {
final TextEditingController _controller = TextEditingController();
List<Marketer> marketerInfo = [
Marketer(name: 'امیررضا مرادی', code: 1),
Marketer(name: 'محمد علی سالان', code: 2),
Marketer(name: 'مهدی قلیزاده ', code: 3),
Marketer(name: 'آرش نوری', code: 4),
Marketer(name: 'نعیم لطفعلی', code: 5),
];
List<Marketer> searchList = [];
#override
void initState() {
_controller.addListener(() {
setState(() {
if (_controller.text.isNotEmpty) {
searchList.clear();
for (var marketer in marketerInfo) {
if (marketer.name.contains(_controller.text)) {
searchList.add(marketer);
}
}
} else {
searchList.clear();
}
});
});
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return ResponsiveWidget(
context: context,
mobile: Directionality(
textDirection: getDirection(context),
child: Scaffold(
appBar: ReportAppBar(
title: 'بازایاب',
hasLeadingWidget: true,
controller: _controller,
isDialog: true,
),
body: Card(
elevation: 8.0,
shadowColor: Colors.grey,
margin: const EdgeInsetsDirectional.only(top: 16),
child: ListView.builder(
itemCount: searchList.isEmpty ? marketerInfo.length : searchList.length,
itemBuilder: (context, index) {
return RadioListTile<Marketer?>(
value: searchList.isNotEmpty ? searchList[index] : marketerInfo[index],
groupValue: widget.selectedValue,
tileColor: Colors.white,
onChanged: (value) {
setState(() {
widget.selectedValue = value!;
Navigator.of(context).pop(value);
});
},
title: Text(
searchList.contains(marketerInfo[index]) ? searchList[index].name : searchList[index].name,
style: const TextStyle(
fontSize: 15.0,
color: MyColor.mine,
fontFamily: Constants.fontFamily,
),
),
);
}),
),
)),
web: Directionality(
textDirection: getDirection(context),
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.white,
title: const Text(
'بازاریاب',
style: TextStyle(
fontSize: 15.0,
color: MyColor.mine,
fontFamily: Constants.fontFamily,
),
),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(50),
child: TextField(
keyboardType: TextInputType.text,
controller: _controller,
decoration: InputDecoration(
suffixIcon: Padding(
padding: const EdgeInsetsDirectional.only(end: 16.0),
child: Image.asset(MyIcons.search, color: Colors.black, alignment: AlignmentDirectional.centerEnd)),
hintText: 'جستوجو در لیست بازاریاب ها',
hintStyle: const TextStyle(
fontFamily: Constants.fontFamily,
fontWeight: FontWeight.w400,
fontSize: 12.0,
),
filled: true,
fillColor: Colors.white,
),
style: const TextStyle(
fontSize: 18.0,
color: MyColor.mine,
fontFamily: Constants.fontFamily,
))),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: searchList.isEmpty ? marketerInfo.length : searchList.length,
itemBuilder: (context, index) {
return RadioListTile<Marketer?>(
value: searchList.isNotEmpty ? searchList[index] : marketerInfo[index],
groupValue: widget.selectedValue,
tileColor: Colors.white,
onChanged: (value) {
setState(() {
widget.selectedValue = value!;
});
},
title: Text(
searchList.isNotEmpty ? searchList[index].name : marketerInfo[index].name,
style: const TextStyle(
fontSize: 15.0,
color: MyColor.mine,
fontFamily: Constants.fontFamily,
),
),
);
}),
),
const Divider(
color: MyColor.mercury,
thickness: 1.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(bottom: 8.0, end: 8.0),
child: MaterialButton(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
onPressed: () {
Navigator.of(context).pop(widget.selectedValue);
},
color: MyColor.main,
child: const Text(
'تأیید',
style: TextStyle(
fontSize: 14.0,
color: Colors.white,
fontFamily: Constants.fontFamily,
),
),
),
)
],
),
],
),
))).get();
}
}
This is the whole page with data and search bar in it
It would be appreciated if anyone could help me
I am creating an app and I am working on the profile setup and am using a tabcontroller. I have my tabcontroller working to navigate my first 3 screens, but for some reason I get a "late initializtion" error for my last screen. I have a custom button that I use for each screen, and the error gets shown once I add the custom button to my last acrren. Could someone explain to me what I need to do to get it working for my last screen? I've attached my code for the tabcontroller, custom button, and my last screen:
Tabcontroller onboarding model:
class AccountOnboarding extends StatefulWidget {
const AccountOnboarding({Key? key}) : super(key: key);
#override
State<AccountOnboarding> createState() => _AccountOnboardingState();
}
class _AccountOnboardingState extends State<AccountOnboarding> {
static const List<Tab> tabs = <Tab>[
Tab(text: 'Name'),
Tab(text: 'Age and Profile'),
Tab(text: 'Bio and Interests'),
Tab(text: 'Selection')
];
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: tabs.length,
child: Builder(builder: (BuildContext context) {
final TabController tabController = DefaultTabController.of(context)!;
tabController.addListener(() {
if (!tabController.indexIsChanging) {}
});
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: const Color(0xff31708c),
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.transparent,
elevation: 0,
title: Row(
children: [
Expanded(
child: Image.asset('assets/images/Logo_Strength.png',
height: 50),
),
Expanded(
flex: 2,
child: RichText(
text: TextSpan(
style: GoogleFonts.montserrat(
fontSize: 30),
children: <TextSpan> [
TextSpan(text: 'Stren',
style: GoogleFonts.montserrat(
color: Colors.white,
fontWeight: FontWeight.bold,
letterSpacing: 1,
shadows: [
Shadow(
color: Colors.black.withOpacity(0.7),
offset: const Offset(1.5, 0.0))
])),
TextSpan(text: ';',
style: GoogleFonts.montserrat(
color: const Color(0xffef6a7a), fontWeight: FontWeight.bold,
letterSpacing: 1,
shadows: [
Shadow(
color: Colors.black.withOpacity(0.7),
offset: const Offset(1.5, 0.0))
])),
TextSpan(text: 'th',
style: GoogleFonts.montserrat(
color: Colors.white,
fontWeight: FontWeight.bold,
letterSpacing: 1,
shadows: [
Shadow(
color: Colors.black.withOpacity(0.7),
offset: const Offset(1.5, 0.0))
]))
],
),
),
),
],
)
),
body: TabBarView(
// physics: const NeverScrollableScrollPhysics(),
children: [
NamePage(tabController: tabController,),
ageAndPicture(tabController: tabController,),
bioAndInterests(tabController: tabController,),
SelectionPage(tabController: tabController,)
],
),
);
}));
}}
Custom Button:
class CustomButton extends StatelessWidget {
final TabController tabController;
const CustomButton({Key? key,
required this.tabController})
: super(key: key);
#override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.white
),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 16),
elevation: 0,
primary: Colors.transparent
),
onPressed: () {
tabController.animateTo(tabController.index + 1);
},
child: Container(
width: double.infinity,
child: Center(
child: Text('Continue',
style: GoogleFonts.montserrat(
color: const Color.fromARGB(255, 20, 83, 106),
fontSize: 19,
fontWeight: FontWeight.w600
),),
),
)
),
);
}
}
Last Screen code:
class SelectionPage extends StatefulWidget {
final TabController tabController;
const SelectionPage({Key? key,
required this.tabController}) : super(key: key);
#override
_SelectionPageState createState() => _SelectionPageState();
}
class _SelectionPageState extends State<SelectionPage>{
List <Item>listOfModel = [];
late TabController tabController;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
String retrieveString;
final data = ModalRoute.of(context)!.settings;
if (data.arguments == null) {
retrieveString = "empty";
} else {
retrieveString = data.arguments as String;
}
listOfModel.add(Item(title: "Maintaining healthy relationships"));
listOfModel.add(Item(title: "Stress and anxiety management"));
listOfModel.add(Item(title: "Maintaing a better work-life balance"));
listOfModel.add(Item(title: "Personal growth and development"));
listOfModel.add(Item(title: "Being happier and more content in life"));
listOfModel.add(Item(title: "Mental and emotional well-being"));
double _height = MediaQuery.of(context).size.height;
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: const Color(0xff31708c),
body: Padding(
padding: EdgeInsets.only(
left: 30,
right: 30,
top: _height * 0.07,
bottom: _height * 0.05),
child: Column(
children: [
Column(
children: [
Column(
children: <Widget>[
Text('Hello there $retrieveString! What all would you like to focus on?',
style: GoogleFonts.montserrat(
color: Colors.white70,
fontSize: 19,
fontWeight: FontWeight.w600
),
textAlign: TextAlign.center,),
const SizedBox(height: 10),
Text("You can pick all that apply:",
style: GoogleFonts.montserrat(
color: Colors.white70,
fontSize: 14.5,
fontWeight: FontWeight.w600
),),
const SizedBox(height: 15,),
GridView.count(
primary: true,
shrinkWrap: true,
padding: const EdgeInsets.all(10),
childAspectRatio: 1.15,
crossAxisCount: 2,
crossAxisSpacing: 25,
mainAxisSpacing: 25,
children: [
gridItem(listOfModel[0],MyFlutterApp.relationships),
gridItem(listOfModel[1],MyFlutterApp2.meditate),
gridItem(listOfModel[2],MyFlutterApp.balance),
gridItem(listOfModel[3],MyFlutterApp2.personal_growth),
gridItem(listOfModel[4],MyFlutterApp.happy),
gridItem(listOfModel[5],MyFlutterApp3.well_rounded),
],
),
const SizedBox(height: 18,),
],
),
CustomButton(tabController: tabController)
],
),
],
),
),
);
}
Widget gridItem(Item item, IconData icon){
return GestureDetector(
onTap: () {
setState(() {
item.isSelected = !item.isSelected;
});
},
child: Stack(
children: [Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: const Color.fromARGB(255, 20, 83, 106),
width: 2.5),
color: item.isSelected ? Color.fromARGB(255, 234, 188, 193) : Colors.white
),
child: Column(
children: [
Align(alignment: Alignment.topCenter,
child: Icon(
icon,
color: const Color(0xff31708c),
size: 45,
),
),
const SizedBox(height: 4,),
Text(item.title,
style: GoogleFonts.montserrat(
fontSize: 14,
fontWeight: FontWeight.w500,
color: const Color(0xff31708c)
),
textAlign: TextAlign.center,),
],
),
),
Positioned(
top: 0,
right: 0,
child: Offstage(
offstage: !item.isSelected,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(width: 2.5),
shape: BoxShape.circle),
child: const Icon(
Icons.check,
color: Colors.green,
),
),
),
)
],
)
);
}
}
class Item{
String title;
bool isSelected;
Item({required this.title, this.isSelected = false});
}
Remove
late TabController tabController;
in SelectionPage and change
CustomButton(tabController: tabController)
in SelectionPage to
CustomButton(tabController: widget.tabController)
I'm making forget password screen for my app and API has integrated in my code. when I click "reset password" button by submitting empty field it running my API code. but I want to run email validation when I submit empty field and click "reset button". how can I do that part in my code. appreciate your help on this.
import 'package:dio/dio.dart';
import 'package:doctor_app/constants/Button.dart';
import 'package:doctor_app/constants/base_api.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import '../constants/colors.dart';
class ForgetPassword extends StatelessWidget {
const ForgetPassword({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.leanBack);
return Scaffold(
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 20,
),
Text('DOCTOR',
style: TextStyle(
fontFamily: 'Dubai',
fontSize: 30,
color: Color(0xff05ABA3),
fontWeight: FontWeight.w500,
)),
],
),
SizedBox(
height: 90,
),
Row(mainAxisAlignment: MainAxisAlignment.start, children: [
Text('Forgot your password?',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 25,
color: Color(0xff040000),
fontWeight: FontWeight.w500,
)),
]),
// Spacer(
// flex: 1,
// ),
SizedBox(
height: 20,
),
Column(
//mainAxisAlignment: MainAxisAlignment.center,
//crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Confirm your email and we will send the Instructions ',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 18,
color: Color(0xff707070),
fontWeight: FontWeight.w100,
)),
],
),
SizedBox(
height: 20,
),
ForgetPasswordForm(), //email
SizedBox(
height: 5,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'didnt receive an email?',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 13,
color: Colors.grey,
fontWeight: FontWeight.w500,
),
),
SizedBox(
width: 5,
),
Align(
alignment: Alignment.bottomLeft,
child: InkWell(
onTap: () {
// add action here whatever you want.
},
child: Text('send again ',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 13,
color: Colors.blue,
fontWeight: FontWeight.w500,
))))
],
),
Spacer(
flex: 1,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Color(0xff05ABA3),
),
height: 5,
width: 120,
),
],
),
],
),
),
);
}
}
class ForgetPasswordForm extends StatefulWidget {
const ForgetPasswordForm({Key? key}) : super(key: key);
#override
_ForgetPasswordFormState createState() => _ForgetPasswordFormState();
}
class _ForgetPasswordFormState extends State<ForgetPasswordForm> {
final _formKey = GlobalKey<FormState>();
//String _userName = "";
String email = "";
Future Resetpassword() async {
try {
var response = await Dio().post(BASE_API+'user/forgotpassword', data: {
"email": email,
});
if (response.data["data"] ==
"Please check your email to reset password.") {
Get.snackbar("success", "Email Sent Successfully!");
//Get.to(VideoScreen());
} else {
Get.snackbar("Error", "No Server Found",
backgroundColor: textWhite.withOpacity(0.5),
borderWidth: 1,
borderColor: textGrey,
colorText: textGrey,
icon: Icon(
Icons.error_outline_outlined,
color: heartRed,
size: 30,
));
}
print("res: $response");
} catch (e) {
Get.snackbar("Error", "Something went wrong.Please contact admin",
backgroundColor: textWhite.withOpacity(0.5),
borderWidth: 1,
borderColor: textGrey,
colorText: textGrey,
icon: Icon(
Icons.error_outline_outlined,
color: heartRed,
size: 30,
));
print(e);
}
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Form(
child: Container(
key: _formKey,
child: Container(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: "Email",
hintStyle: TextStyle(
color: textGrey,
fontFamily: "Dubai",
fontSize: 14)),
validator: (String? Email) {
if (Email != null && Email.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
print(email);
},
),
SizedBox(
height: 50,
),
Container(
child: GestureDetector(
child: ButtonM("Reset Password"),
onTap: () async {
Resetpassword();
},
),
)
]),
)))));
}
}
Just wrap your ResetPassword() method like below:
if (_formKey.currentState!.validate()) {
Resetpassword();
}
This will check the validation.
Make sure key in attached to Form widget not Container
class ForgetPasswordForm extends StatefulWidget {
const ForgetPasswordForm({Key? key}) : super(key: key);
#override
_ForgetPasswordFormState createState() => _ForgetPasswordFormState();
}
class _ForgetPasswordFormState extends State<ForgetPasswordForm> {
final _formKey = GlobalKey<FormState>();
String email = "";
Future Resetpassword() async {
print("123");
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Container(
child: Container(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: "Email",
hintStyle: TextStyle(
color: Colors.grey,
fontFamily: "Dubai",
fontSize: 14)),
validator: (String? Email) {
if (Email != null && Email.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
print(email);
},
),
SizedBox(
height: 50,
),
Container(
child: TextButton(
child: Text("Reset Password"),
onPressed: () async {
if (_formKey.currentState!.validate()) {
Resetpassword();
}
},
),
)
]),
)))));
}
}
Add variable
final GlobalKey<FormState> keys = GlobalKey<FormState>();
validate like that
if (_keys.currentState!.validate()) {
Resetpassword();
}
I'm using flutter to make an app
there is an error related with provider
I tried to write Provider.of<Category>(context, listen: false); to fix this error
but error keeps showing
how can I fix this error?
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:get/get.dart';
import 'result_screen.dart';
import 'package:youtube_ad2/provider/food_provider.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
InterstitialAd? interstitialAd;
bool isLoaded = false;
#override
void initState() {
super.initState();
Provider.of<Category>(context, listen: false);
}
#override
void didChangeDependencies() {
//TODO implement didChangeDependencies
super.didChangeDependencies();
InterstitialAd.load(
adUnitId: InterstitialAd.testAdUnitId,
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
setState(() {
isLoaded = true;
interstitialAd = ad;
});
print("Ad Loaded");
},
onAdFailedToLoad: (error) {
print("Interstitial Failed to load");
},
),
);
}
String? value;
List<String> listItem = ["전체", "중국", "한국", "일본", "동남아", "유럽", "아메리카"];
#override
Widget build(BuildContext context) {
return Container(
// decoration: BoxDecoration(
// image: DecorationImage(
// fit: BoxFit.cover,
// image: AssetImage('assets/images/bg3.png'), // 배경 이미지
// ),
// ),
child: Scaffold(
backgroundColor: Colors.orange[300],
appBar: AppBar(
automaticallyImplyLeading: false,
elevation: 0,
title: Center(
child: Text(
'오늘의 식사',
style: TextStyle(
fontFamily: 'Chilgok',
color: Colors.yellow.shade300,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/logo.png',
width: MediaQuery.of(context).size.width / 3,
),
Text('Open!'),
]),
style: ElevatedButton.styleFrom(
side: BorderSide(
width: 5,
color: Colors.red,
),
elevation: 40,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100)),
primary: Colors.orange[300],
padding: const EdgeInsets.only(
top: 9,
bottom: 15,
left: 20,
right: 20,
),
),
onPressed: () {
if (isLoaded) {
interstitialAd!.show();
Provider.of<Category>(context, listen: false);
context
.read<FoodResult>()
.selectFood(context.read<Category>().category);
Get.to(() => ResultScreen());
} else {
Provider.of<Category>(context, listen: false);
context
.read<FoodResult>()
.selectFood(context.read<Category>().category);
Get.to(() => ResultScreen());
}
},
),
Container(
padding: EdgeInsets.only(
left: 10,
right: 10,
top: 3,
bottom: 5,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: Colors.red,
width: 4,
),
),
width: MediaQuery.of(context).size.width / 3,
height: 40,
child: DropdownButton<String>(
underline: DropdownButtonHideUnderline(child: Container()),
dropdownColor: Colors.grey[200],
borderRadius: BorderRadius.circular(10),
elevation: 0,
hint: Text(
"음식종류",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
value: value,
iconSize: 20,
icon: Icon(Icons.arrow_drop_down, color: Colors.red),
isExpanded: true,
items: listItem.map(valueItem).toList(),
onChanged: (value) => setState(() => this.value = value),
),
)
],
),
)),
);
}
DropdownMenuItem<String> valueItem(String item) => DropdownMenuItem(
value: item,
child: Text(
item,
style: TextStyle(
color: Colors.black87,
fontSize: 20,
),
),
);
}
try this code
#override void initState(){
Future.delayed(Duration.zero).then((_) =>
Provider.of<Category>(context, listen: false););
super.initState();
}
//in this code i am tring to use connectivity. Android recommended me to add some classes, //getters setter, I added them at the end of the code automatically
import 'package:firebase_auth/firebase_auth.dart';[enter image description here][1]
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'signup.dart';
import 'home.dart';
import 'dart:async';
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class Login extends StatefulWidget {
const Login({Key? key}) : super(key: key);
#override
_LoginState createState() => _LoginState();
}
//loginstate
class _LoginState extends State<Login> {
ConnectivityResult? _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
#override
void initState() {
super.initState();
initConnectivity();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
}
#override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initConnectivity() async {
late ConnectivityResult result;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
developer.log('Couldn\'t check connectivity status', error: e);
return;
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
return Future.value(null);
}
return _updateConnectionStatus(result);
}
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
setState(() {
_connectionStatus = result;
});
}
//Login function
static Future<User?> loiginUsingEmailPassword(
{required String email,
required String password,
required BuildContext context}) async {
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
try {
UserCredential userCredential = await auth.signInWithEmailAndPassword(
email: email, password: password);
user = userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == "user-not-found") {
print("No user found for that email");
}
}
return user;
}
#override
Widget build(BuildContext context) {
//create textfield controller
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
return Scaffold(
resizeToAvoidBottomInset: false,
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(15.0, 110.0, 0.0, 0.0),
child: Text(
'Bon Appétit',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 50.0,
),
),
),
//new container
Container(
padding: EdgeInsets.only(top: 35.0, left: 20.0, right: 20.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xFFcaa052)),
),
labelText: 'EMAIL',
labelStyle: TextStyle(
fontFamily: 'Alegreya Sans',
fontWeight: FontWeight.bold,
color: Color(0xFFcaa052),
),
),
),
SizedBox(
height: 20.0,
),
TextField(
controller: _passwordController,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xFFcaa052)),
),
labelText: 'PASSWORD',
labelStyle: TextStyle(
fontFamily: 'Alegreya Sans',
fontWeight: FontWeight.bold,
color: Color(0xFFcaa052),
),
),
obscureText: true,
),
SizedBox(
height: 5.0,
),
Container(
alignment: Alignment(1.0, 0.0),
padding: EdgeInsets.only(top: 15.0, left: 20.0),
child: InkWell(
child: Text(
'Forgot Password',
style: TextStyle(
color: Color(0xFF5E0B0B),
fontWeight: FontWeight.bold,
fontFamily: 'Alegreya Sans',
decoration: TextDecoration.underline,
),
),
),
),
SizedBox(
height: 40.0,
),
],
),
),
SizedBox(
height: 15.0,
),
Container(
height: 40.0,
width: 400.0,
child: Material(
borderRadius: BorderRadius.circular(20.0),
shadowColor: Color(0xFFffffb1),
color: Color(0xFFffd180),
elevation: 7.0,
child: InkWell(
onTap: () async {
User? user = await loiginUsingEmailPassword(
email: _emailController.text,
password: _passwordController.text,
context: context);
print(user);
if (user != null) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Home()),
);
}
},
child: Center(
child: Text(
'LOGIN',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontFamily: 'Alegreya Sans',
),
),
),
),
),
),
Container(
child: Text('Connection Status: ${_connectionStatus.toString()}'),
),
SizedBox(
height: 15.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'New member?',
style: TextStyle(fontFamily: 'Alegreya Sans'),
),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Signup()),
);
},
child: Text(
'Sign up',
style: TextStyle(
color: Color(0xFF5E0B0B),
fontWeight: FontWeight.bold,
fontFamily: 'Alegreya Sans',
decoration: TextDecoration.underline,
),
),
),
],
),
],
),
),
);
}
}
//i think because of below code i got error
class ConnectivityResult {
static ConnectivityResult? none;
}
class Connectivity {
get onConnectivityChanged => null;
checkConnectivity() {}
}