Flutter button doesn't work when passing variables between files - flutter

I'm building a workout app with a sign out button and a delete exercise button. I've made a single file instead of 2 and passed variable. I did this so That I don't have to make 2 files.
the problem is with function; in the onPressed call back in dialog.instance.dart
if I don't pass the variables it works fine. but I don't wanna make 2 separate files.
I tried this but it didn't work to plan:
dialog_instance.dart
Future<void> DialogInstance(BuildContext context, void Function()? function,
String name, String description) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
backgroundColor: Colors.blueGrey,
title: Text(
name,
style: const TextStyle(color: Colors.white),
),
actions: [
Row(
children: [
const SizedBox(width: 16.0),
Text(
'Are you sure $description',
style: const TextStyle(color: Colors.white),
)
],
),
const SizedBox(height: 20),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () {
function;
},
style:
OutlinedButton.styleFrom(backgroundColor: Colors.red),
child: const Text('Yes',
style: TextStyle(color: Colors.white)),
),
),
],
),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Cancel',
style: TextStyle(color: Colors.white)),
),
),
],
),
],
);
});
}
workout_page.dart
class WorkoutPage extends StatefulWidget {
const WorkoutPage({Key? key}) : super(key: key);
#override
State<WorkoutPage> createState() => _WorkoutPageState();
}
User user = FirebaseAuth.instance.currentUser!;
String signOutText = 'Sign Out';
const signOutDescription = 'you want to sign out?';
class _WorkoutPageState extends State<WorkoutPage> {
#override
Widget build(BuildContext context) {
void signOutFunction() {
AuthService.signOutMethod();
Navigator.of(context)
.pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
}
return Scaffold(
backgroundColor: backgroundColor,
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(user.email!, style: const TextStyle(fontSize: 14)),
backgroundColor: backgroundColor,
actions: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: GradientElevatedButton(
onPressed: () {
DialogInstance(context, signOutFunction, signOutText,
signOutDescription);
},
child: const Text('Sign out')),
)
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const ExercisePage()));
},
child: const Icon(
Icons.add,
color: Colors.black,
),
),
);
}
}
cardiovascular_card.dart
class CardiovascularCard extends StatefulWidget {
AsyncSnapshot<QuerySnapshot> snapshot;
int index;
CardiovascularCard(this.snapshot, this.index, {Key? key}) : super(key: key);
#override
State<CardiovascularCard> createState() => _CardiovascularCardState();
}
String deleteExerciseText = 'Delete exercise';
final uid = FirebaseAuth.instance.currentUser?.uid;
TextEditingController _calorieController = TextEditingController();
TextEditingController _timeController = TextEditingController();
String deleteExerciseDescription = 'you want to delete this exercise?';
class _CardiovascularCardState extends State<CardiovascularCard> {
#override
Widget build(BuildContext context) {
String deleteExerciseText = 'Delete exercise';
final uid = FirebaseAuth.instance.currentUser?.uid;
final data = widget.snapshot.data;
final exerciseId = data!.docs[widget.index].reference.id;
void deleteExerciseFunction() {
FirebaseFirestore.instance
.runTransaction((Transaction myTransaction) async {
myTransaction.delete(data.docs[widget.index].reference);
});
}
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(children: [
Card(
elevation: 8,
color: const Color.fromARGB(255, 81, 108, 122),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
data.docs[widget.index]['exerciseName'],
style: const TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
),
),
const Divider(thickness: 1.0),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: const [
Text(
'Calories',
style: TextStyle(color: Colors.white),
),
Text(
'Time',
style: TextStyle(color: Colors.white),
),
],
),
Slidable(
endActionPane: ActionPane(
motion: const ScrollMotion(),
children: [
SlidableAction(
onPressed: (context) {
DialogInstance(context, deleteExerciseFunction,
deleteExerciseText, deleteExerciseDescription);
},
label: 'Delete',
backgroundColor: Colors.red,
icon: Icons.delete,
)
],
),
child: ListTile(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.145,
child: TextField(
style: const TextStyle(fontWeight: FontWeight.bold),
cursorColor: Colors.white,
onSubmitted: (value) async {
FirebaseFirestore.instance.runTransaction(
(Transaction myTransaction) async {
FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('workout')
.doc(exerciseId)
.update({'caloriesBurnt': value});
});
},
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
controller: _calorieController,
decoration: InputDecoration(
focusedBorder: const UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
hintText: data.docs[widget.index]['caloriesBurnt']
.toString()),
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.145,
child: TextField(
style: const TextStyle(fontWeight: FontWeight.bold),
cursorColor: Colors.white,
onSubmitted: (value) async {
FirebaseFirestore.instance.runTransaction(
(Transaction myTransaction) async {
FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('workout')
.doc(exerciseId)
.update({'time': value});
});
},
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
controller: _timeController,
decoration: InputDecoration(
focusedBorder: const UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
hintText:
data.docs[widget.index]['time'].toString()),
),
),
],
),
),
),
],
),
),
]),
);
}
}

If i understand correctly - function named function is not called.
You have to call the function with function() or tear-off
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () {
function();
},
or
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed:function,

Related

Flutter complains about undefined var, however i defined it

I created 2 pages, in first one i have TextField to pass data to second one.
In second file i created class and Text class to output the phone number, but compiler says it's undefined. Both Class and Text() are in same dart file.
Class with constructor:
class ProfilePage extends StatefulWidget {
final String phonenum;
const ProfilePage({Key? key, required this.phonenum}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
Text Class that must output name
Text(phonenum),
Function in first file to pass the phone number
void _submit() {
Route route = MaterialPageRoute(builder: (context) => ProfilePage(phonenum: _phonenumber,)); // (constructors name: class member)
Navigator.push(context, route);
}
Page 1 code:
import 'package:flutter/material.dart';
import 'package:untitled/pages/ProfilePage.dart';
import 'package:untitled/pages/StadiumPage.dart';
void main() {
runApp(LogInPage());
}
class LogInPage extends StatefulWidget {
const LogInPage({Key? key}) : super(key: key);
#override
_LogInPageState createState() => _LogInPageState();
}
class _LogInPageState extends State<LogInPage> {
String _phonenumber = '';
#override
Widget build(BuildContext context) {
double _wid = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 180,
),
Container(
margin: EdgeInsets.only(left: 40),
width: _wid,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'stadion.kg',
style: TextStyle(
fontSize: 35,
color: Colors.redAccent,
fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Text(
'Добро пожаловать!',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
SizedBox(height: 50),
Text(
'Номер телефона:',
style: TextStyle(fontSize: 15, color: Colors.redAccent),
),
],
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 40),
child: TextField(
keyboardType: TextInputType.phone,
onChanged: (value) {
_phonenumber = value;
},
maxLength: 9,
decoration: InputDecoration(
prefixIcon: Icon(Icons.phone), prefixText: '+996'))),
SizedBox(height: 45),
ElevatedButton(
onPressed: _submit,
child: Text('Войти'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 140, vertical: 15),
primary: Colors.redAccent),
),
SizedBox(height: 10),
TextButton(
onPressed: _submitnoregist,
child: Text(
'Продолжить без регистрации!',
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w400),
))
],
),
),
);
}
void _submitnoregist() {
Route route = MaterialPageRoute(builder: (context) => HomePage()); // (constructors name: class member)
Navigator.push(context, route);
}
void _submit() {
Route route = MaterialPageRoute(builder: (context) => ProfilePage(phonenum: _phonenumber,)); // (constructors name: class member)
Navigator.push(context, route);
}
}
Page 2 Code:
import 'package:flutter/material.dart';
import 'package:untitled/pages/FavoritesPage.dart';
import 'package:untitled/pages/MapPage.dart';
import 'package:untitled/pages/StadiumPage.dart';
class ProfilePage extends StatefulWidget {
final String phonenum;
const ProfilePage({Key? key, required this.phonenum}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
int _selind = 0;
List<Widget> _widgetopt = <Widget>[
Text('Index 4'),
Text('Index 2'),
Text('Index 3'),
Text('Index 4'),
];
void OnBeingTapped(int index) {
setState(() {
_selind = index;
if (index == 0) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
} else if (index == 1) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => MapPage()));
} else if (index == 2) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => FavoritesPage()));
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.indigo[50],
appBar: AppBar(
title: Text('Профиль', style: TextStyle(color: Colors.black)),
backgroundColor: Colors.white,
toolbarHeight: 80,
centerTitle: true,
),
body: Column(
children: [
SizedBox(
height: 20,
),
Center(
child: Column(
children: [
CircleAvatar(
backgroundImage: AssetImage('lib/assets/ava.jpg'),
maxRadius: 60,
),
SizedBox(
height: 20,
),
Text(
'Неизвестный\nпользователь',
style: TextStyle(fontWeight: FontWeight.w500, fontSize: 25),
),
SizedBox(
height: 10,
),
Text(phonenum,
style: TextStyle(color: Colors.redAccent, fontSize: 20)),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 1.5,
offset: Offset(
1.5, // horizontal, move right 10
1.5, // vertical, move down 10
),
)
],
color: Colors.white,
border: Border.all(color: Colors.white70),
borderRadius: BorderRadius.all(Radius.circular(20))),
child: ButtonBar(
alignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
TextButton(
onPressed: () {},
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text('Пользовательское соглашение',
style: TextStyle(
color: Colors.black, fontSize: 20)),
Icon(
Icons.arrow_forward_ios_rounded,
color: Colors.black,
)
]),
),
TextButton(
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Пригласить друзей',
style: TextStyle(
color: Colors.black, fontSize: 20)),
Icon(
Icons.arrow_forward_ios_rounded,
color: Colors.black,
)
],
),
),
TextButton(
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Выйти',
style: TextStyle(
color: Colors.black, fontSize: 20)),
Icon(
Icons.arrow_forward_ios_rounded,
color: Colors.black,
)
],
),
),
SizedBox(
height: 30,
),
],
),
),
)
],
),
)
],
),
bottomNavigationBar: SizedBox(
height: 80,
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.white,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.add_box_outlined,
color: Colors.black,
),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Icons.location_on_outlined,
color: Colors.black,
),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Icons.favorite_outline,
color: Colors.black,
),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Icons.person_outline_outlined,
color: Colors.black,
),
label: ''),
],
currentIndex: _selind,
selectedItemColor: Colors.yellow,
onTap: OnBeingTapped,
),
),
),
title: 'Stadium',
);
}
}
phonenum is a class variable of ProfilePage and _ProfilePageState cannot access it directly. Because _ProfilePageState is a State class of ProfilePage you have a property called widget that you can use to access variables of ProfilePage class.
So your code should be like that:
Text(
widget.phonenum,
...
...
)

Flutter: Whenever I pressed on Home button I redirect to Login Screen

I made a simple app where I am using firebase authentication
I used Side drawer in this app
The app work fine on all other tabs but when ever I pressed home button from side drawer instead of going to home screen(initial page route) Login Page comes out and If on the same time I Hot Reload the app then I automatically re-direct to home Screen
2 days ago the app is working currently fine but today this is happening.
Here is my Main.dart file:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
static const myApproute = 'myapproue';
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final screen = [
const HomePage(),
AnnoucementScreen(),
const AdminScreen(),
const SettingsScreen(),
];
int currentIndex = 0;
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
pageTransitionsTheme: PageTransitionsTheme(
builders: {
TargetPlatform.android: CustomPageTransitionBuilder(),
},
),
),
home: StreamBuilder(
stream: Login().firebaseAuth.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Scaffold(
body: screen[currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showUnselectedLabels: false,
selectedItemColor: Colors.black,
unselectedItemColor: Colors.grey,
currentIndex: currentIndex,
// onTap: (value) => setState(() => currentIndex = value),
onTap: (value) {
setState(() {
currentIndex = value;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.event), label: 'Announcement'),
BottomNavigationBarItem(
icon: Icon(Icons.admin_panel_settings), label: 'Admin'),
BottomNavigationBarItem(
icon: Icon(Icons.settings_accessibility_sharp),
label: 'Profile'),
],
),
);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return const LoginScreen();
}),
routes: {
MyApp.myApproute: (context) => const MyApp(),
LoginScreen.rout: (context) => const LoginScreen(),
SignUpScreen.signUpRout: (context) => const SignUpScreen(),
BabaHassanLifeIntroScreen.babaHassanPageRout: (context) =>
const BabaHassanLifeIntroScreen(),
BabahafizIqbalLifeIntroScreen.babaHafizIqbalRout: (context) =>
const BabahafizIqbalLifeIntroScreen(),
BabaHassanMizajScreen.babaSaiMijazRout: (context) =>
const BabaHassanMizajScreen(),
BabaHassanLifeIncident.babaHassanLifeincident: (context) =>
const BabaHassanLifeIncident(),
BabaHafizIqbalMizajScreen.babaHafizIqbalMizajScreenRoute: (context) =>
const BabaHafizIqbalMizajScreen(),
BabaHafizIqbalLifeIncidentScreen.babaHafizIqbalLifeIncidentScreenRoute:
(context) => const BabaHafizIqbalLifeIncidentScreen(),
TasheerActivitiesScree.tasheerActivitiesScreeRoute: (context) =>
const TasheerActivitiesScree(),
DarbarIntroScreen.darbarIntroScreenRoute: (context) =>
const DarbarIntroScreen(),
ShujraShareefScreen.shujraShareefScreenRoute: (context) =>
const ShujraShareefScreen(),
MusabaEelaafScreen.musabaEelaafScreenRoute: (context) =>
const MusabaEelaafScreen(),
MusabaEelaafBunyadScreen.musbaEelaafBunyadScreenRoute: (context) =>
const MusabaEelaafBunyadScreen(),
BooksScreen.booksScreenRoute: (context) => const BooksScreen(),
SettingMenu.settingMenuRoute: (context) => SettingMenu(),
AdminHome.adminHomeRoute: (context) => AdminHome(),
CreateEvent.createEventRoute: (context) => const CreateEvent(),
SettingMenuAccount.settingMenuAccountRoute: (context) =>
const SettingMenuAccount(),
FeedBackForm.feedBackFormRoute: (context) => const FeedBackForm(),
HomePage.homeRout: (context) => const HomePage(),
},
);
}
}
Here is my sideDrawer.dart file:
class SideDrawer extends StatefulWidget {
const SideDrawer({super.key});
#override
State<SideDrawer> createState() => _SideDrawerState();
}
class _SideDrawerState extends State<SideDrawer> {
var _expanded = false;
var _expandedTwo = false;
//var _expandedThree = false;
var _expandedFive = false;
#override
Widget build(BuildContext context) {
MediaQueryData mediaQueryData;
mediaQueryData = MediaQuery.of(context);
return Drawer(
width: mediaQueryData.size.width * 0.7,
child: ListView(
children: <Widget>[
DrawerHeader(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
gradient: LinearGradient(colors: [
Colors.black,
Color.fromRGBO(255, 243, 18, 3),
], begin: Alignment.topLeft, end: Alignment.bottomRight),
),
child: Padding(
padding: const EdgeInsets.only(top: 70),
child: Column(
children: const [
Text(
"Musaba-Tul-Eelaad",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
textAlign: TextAlign.justify,
),
Text(
"مثابۃ ایلاف",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
textAlign: TextAlign.justify,
),
],
),
),
),
ListTile(
title: const Text(
"Home Page",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
onTap: () {
Navigator.of(context).pushReplacementNamed('/');
},
),
const Divider(),
ListTile(
title: const Text(
"Introduction (تعارف)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
trailing: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onTap: () {
setState(() {
_expanded = !_expanded;
});
},
),
if (_expanded)
Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'شجرہ شریف',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
ShujraShareefScreen.shujraShareefScreenRoute);
},
),
),
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'مثابۃ ایلاف',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
MusabaEelaafScreen.musabaEelaafScreenRoute);
},
),
),
],
),
const Divider(),
ListTile(
title: const Text(
"About Ourself (ہمارے بارے میں)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
trailing:
Icon(_expandedTwo ? Icons.expand_less : Icons.expand_more),
onTap: () {
setState(() {
_expandedTwo = !_expandedTwo;
});
},
),
if (_expandedTwo)
Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 20),
child: ListTile(
title: const Text(
'باباسائیں حسن الدینؒ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
onTap: () {
Navigator.of(context).pushReplacementNamed(
BabaHassanLifeIntroScreen.babaHassanPageRout);
},
),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(right: 20),
child: ListTile(
title: const Text(
'حافظ سائیں محمداقبالؒ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
onTap: () {
Navigator.of(context).pushReplacementNamed(
BabahafizIqbalLifeIntroScreen.babaHafizIqbalRout);
}),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'تشہیر اور سرگرمیاں',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
TasheerActivitiesScree.tasheerActivitiesScreeRoute);
},
),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'دربار باباسائیں حسن الدینؒ و حافظ سائیں محمد اقبالؒ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
DarbarIntroScreen.darbarIntroScreenRoute);
},
),
),
],
),
const Divider(),
ListTile(
title: const Text(
"Gallery (گیلری)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
// trailing:
// Icon(_expandedThree ? Icons.expand_less : Icons.expand_more),
onTap: () {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Attention Required"),
content: const Text(
"The gallery content is currently Under-Development.You will be notified when its ready for you. Please make sure you enable notification to get Future updates"),
actions: [
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: const Text("Okay"))
],
),
);
// setState(() {
// _expandedThree = !_expandedThree;
// });
},
),
const Divider(),
ListTile(
title: const Text(
"Books (قطب)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
onTap: () {
Navigator.of(context)
.pushReplacementNamed(BooksScreen.booksScreenRoute);
},
),
const Divider(),
ListTile(
title: const Text(
"Cermony (تقریب)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
trailing:
Icon(_expandedFive ? Icons.expand_less : Icons.expand_more),
onTap: () {
setState(() {
_expandedFive = !_expandedFive;
});
},
),
if (_expandedFive)
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'۱۳رجب۱۴۴۱۔۲۰۱۹',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () => {},
),
)
],
),
],
),
);
}
}
Here is my Login Screen File:
class LoginScreen extends StatefulWidget {
static const rout = '/login-screen';
const LoginScreen({super.key});
#override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final Map<String, String> _loginData = {'email': '', 'password': ''};
GlobalKey topWidgetKey = GlobalKey();
GlobalKey bottomWidgetKey = GlobalKey();
double topWidgetHeight = 0.0;
double bottomWidgetHeight = 0.0;
double spacer = 0.0;
var isLoading = false;
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() {
final topWidgetKeyContextt = topWidgetKey.currentContext;
if (topWidgetKeyContextt != null) {
final box = topWidgetKeyContextt.findRenderObject() as RenderBox;
topWidgetHeight = box.size.height;
}
final bottomWidgetKeyContextt = bottomWidgetKey.currentContext;
if (bottomWidgetKeyContextt != null) {
final box = bottomWidgetKeyContextt.findRenderObject() as RenderBox;
bottomWidgetHeight = box.size.height;
}
spacer = MediaQuery.of(context).size.height -
AppBar().preferredSize.height -
topWidgetHeight -
bottomWidgetHeight -
MediaQuery.of(context).viewPadding.top -
MediaQuery.of(context).viewPadding.bottom;
});
}
});
super.initState();
}
final _emailController = TextEditingController();
final _form = GlobalKey<FormState>();
final _passwordController = TextEditingController();
var visible = true;
final emailVerificationSyntax = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+");
void _errorDialog(String message) {
showDialog(
context: context,
builder: ((ctx) => AlertDialog(
title: const Text("An Error Accourd"),
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: const Text("Okay"))
],
)),
);
}
void push() {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (_) => const MyApp(),
),
(route) => false);
}
Future<void> _saveData() async {
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
setState(() {
isLoading = true;
});
try {
await Login().signInUser(_loginData['email'].toString(),
_loginData['password'].toString(), context);
push();
} catch (e) {
var errorMessage = 'Authentication Failed';
if (e.toString().contains('INVALID_EMAIL')) {
errorMessage = 'The email adress is not valid';
} else if (e.toString().contains('EMAIL_NOT_FOUND')) {
errorMessage = 'No User found with this Email';
} else if (e.toString().contains('INVALID_PASSWORD')) {
errorMessage = 'Invalid Password';
}
_errorDialog(errorMessage);
}
setState(() {
isLoading = false;
});
}
#override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromRGBO(255, 243, 18, 3),
body: SingleChildScrollView(
child: Form(
key: _form,
child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 90),
child: Image.asset('assets/images/Logo.png'),
),
const SizedBox(
height: 10,
),
const SafeArea(
child: Padding(
padding: EdgeInsets.only(left: 3, right: 250, top: 10),
child: Text(
"Login",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 40),
// textAlign: TextAlign.center,
),
),
),
const Padding(
padding: EdgeInsets.only(left: 20, right: 200, top: 3),
child: Text(
"Please Login to continue",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 15),
// textAlign: TextAlign.center,
),
),
const SizedBox(
height: 15,
),
Card(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
),
),
shadowColor: Colors.grey,
elevation: 10,
child: TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email-Address',
prefixIcon: Icon(
(Icons.person),
),
border: OutlineInputBorder(borderSide: BorderSide.none),
),
onSaved: (newValue) {
_loginData['email'] = newValue!;
},
validator: (value) {
if (!emailVerificationSyntax.hasMatch(value as String)) {
return "Incorrect Email-Adress Syntax";
}
if (value.isEmpty) {
return 'Please Enter Your Email Adress';
}
return null;
},
),
),
const SizedBox(
height: 15,
),
Card(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
),
),
shadowColor: Colors.grey,
elevation: 10,
child: TextFormField(
controller: _passwordController,
obscureText: visible,
keyboardType: TextInputType.streetAddress,
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: const Icon(
(Icons.password),
),
suffixIcon: IconButton(
onPressed: () {
setState(() {
visible = !visible;
});
},
icon: const Icon(Icons.visibility)),
border: const OutlineInputBorder(borderSide: BorderSide.none),
),
validator: (value) {
if (value!.isEmpty) {
return "Please Enter Your Passowrd";
}
return null;
},
onSaved: (newValue) {
_loginData['password'] = newValue!;
},
),
),
const SizedBox(
height: 15,
),
isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: () => _saveData(),
style: ElevatedButton.styleFrom(
// backgroundColor: Color.fromARGB(255, 246, 214, 4)),
backgroundColor: Colors.white),
child: const Text(
'Login',
style: TextStyle(
color: Colors.black,
fontSize: 30,
fontWeight: FontWeight.normal,
),
),
),
const SizedBox(
height: 100,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.only(bottom: 20),
child: Text(
"Don't have an account?",
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 20),
child: TextButton(
onPressed: () {
Navigator.of(context)
.pushReplacementNamed(SignUpScreen.signUpRout);
},
child: const Text(
"Sign Up",
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold),
)),
)
],
)
]),
),
),
);
}
}
This is my project I m currently working on and now when the time comes to deliver it this is happen I tried a-lot but not figure it out.

flutter bloc doesn't update the ui?

when i navigate from NewSales screen to CreateItem screen and add item and press the add button
the item is added to sqflite database then it navigates back to new sales but the state is not updated , it's updated only if i restarted the app
the NewSales screen
class _NewSalesState extends State<NewSales> {
final controller = TextEditingController();
showAlertDialog(BuildContext context,String name) {
// Create button
// Create AlertDialog
AlertDialog alert = AlertDialog(
title: const Text("Alert"),
content: const Text("you want to delete this item?"),
actions: [
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green)),
child: const Text("CANCEL", style: TextStyle(color: Colors.white)),
onPressed: () {
Navigator.of(context).pop();
},
),
BlocBuilder<SalesCubit, SalesState>(
builder: (context, state) {
final bloc=BlocProvider.of<SalesCubit>(context);
return TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red)),
child: const Text(
"DELETE",
style: TextStyle(color: Colors.white),
),
onPressed: () {
Navigator.of(context).pop();
bloc.deleteItem(name).then((value) {
bloc.getAllItems();
});
},
);
},
)
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
// #override
#override
Widget build(BuildContext context) {
final deviceSize = MediaQuery
.of(context)
.size;
return BlocConsumer<SalesCubit, SalesState>(
listener: (context, state) {},
builder: (context, state) {
final bloc = BlocProvider.of<SalesCubit>(context);
if (state is SalesInitial) {
bloc.getAllItems();
}
return Scaffold(
drawer: const navDrawer(),
appBar: AppBar(
title: const Text("Ticket"),
actions: [
IconButton(
onPressed: () async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print('barcodeScanRes $barcodeScanRes');
print(bloc.bsResult);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
// 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;
bloc.toggleSearch();
controller.text = barcodeScanRes;
bloc.filterItems(barcodeScanRes);
},
icon: const Icon(Icons.scanner),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: IconButton(
onPressed: () {
Navigator.of(context).pushNamed(Routes.addCustomerRoute);
},
icon: Icon(Icons.person_add)),
),
],
),
body: Column(
children: [
// the first button
Container(
width: double.infinity,
height: deviceSize.height * .1,
color: Colors.grey,
child: GestureDetector(
onTap: ()=>displayMessage("an item was charged successfully", context),
child: Padding(
padding: const EdgeInsets.all(10),
child: Container(
color: Colors.green,
child: const Center(
child: Text("charge",style: TextStyle(color: Colors.white),),
),
),
),
),
),
// the second container
SizedBox(
width: deviceSize.width,
height: deviceSize.height * .1,
child: Row(
children: [
DecoratedBox(
decoration:
BoxDecoration(border: Border.all(color: Colors.grey)),
child: SizedBox(
width: deviceSize.width * .8,
child: bloc.isSearch
? TextFormField(
autofocus: true,
controller: controller,
decoration:
const InputDecoration(hintText: "Search"),
onChanged: (value) {
bloc.filterItems(controller.text);
},
)
: DropdownButtonFormField<String>(
// underline: Container(),
// value: "Discounts",
hint: const Padding(
padding: EdgeInsets.only(left: 10),
child: Text('Please choose type'),
),
items: <String>['Discounts', 'All Items']
.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) {},
),
),
),
DecoratedBox(
decoration:
BoxDecoration(border: Border.all(color: Colors.grey)),
child: SizedBox(
width: deviceSize.width * .2,
child: IconButton(
onPressed: () {
bloc.toggleSearch();
if (!bloc.isSearch) {
bloc.filterItems('');
}
},
icon: Icon(
!bloc.isSearch ? Icons.search : Icons.close)),
),
)
],
),
),
// the third container
if (state is IsLoading || state is SalesInitial)
const Center(
child: CircularProgressIndicator(
color: Colors.green,
backgroundColor: Colors.green,
),
),
if (state is Loaded || state is IsSearch || state is SearchDone)
bloc.items.isEmpty
? const Center(
child: Text("no items added yet"),
)
: Expanded(
child: bloc.filteredItems.isEmpty
? const Center(
child: Text(
"no items found with this name",
style: TextStyle(color: Colors.green),
),
)
: ListView.builder(
itemCount: bloc.filteredItems.length,
itemBuilder: (context, i) {
final item = bloc.filteredItems[i];
return Card(
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.green,
radius: 20,
child: Text(item.price),
),
title: Text(item.name),
subtitle: Text(item.barcode),
trailing: Column(
children: [
IconButton(
onPressed: () {
showAlertDialog(context,item.name);
// bloc.deleteItem(item.name).then((value) {
// bloc.getAllItems();
// });
},
icon: const Icon(
Icons.delete,
color: Colors.red,
))
],
)),
);
}))
],
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: ()async {
Navigator.of(context).pushNamed(Routes.createItemRoute);
},
),
);
},
);
}
}
the CreateItem screen
class _CreateItemState extends State<CreateItem> {
final nameController = TextEditingController();
final priceController = TextEditingController();
final costController = TextEditingController();
final skuController = TextEditingController();
final barcodeController = TextEditingController();
final inStockController = TextEditingController();
bool each = true; // bool variable for check box
bool isColor = true;
bool switchValue = false;
File? file;
String base64File = "";
String path = "";
final _formKey = GlobalKey<FormState>();
#override
void dispose() {
nameController.dispose();
priceController.dispose();
costController.dispose();
skuController.dispose();
barcodeController.dispose();
inStockController.dispose();
super.dispose();
}
Future pickImage(ImageSource source) async {
File? image1;
XFile imageFile;
final imagePicker = ImagePicker();
final image = await imagePicker.pickImage(source: source);
imageFile = image!;
image1 = File(imageFile.path);
List<int> fileUnit8 = image1.readAsBytesSync();
setState(() {
base64File = base64.encode(fileUnit8);
});
}
#override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return BlocProvider(
create: (BuildContext context) => CreateItemCubit(),
child: Builder(builder: (context){
final bloc=BlocProvider.of<CreateItemCubit>(context);
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () => Navigator.of(context).pushNamedAndRemoveUntil(Routes.newSalesRoute, (route) => false),
icon: const Icon(Icons.arrow_back)),
title: const Text("Create Item"),
actions: [TextButton(onPressed: () {}, child: const Text("SAVE"))],
),
body: Padding(
padding: const EdgeInsets.all(10),
child: Form(
key: _formKey,
child: ListView(
children: [
TextFormField(
controller: nameController,
cursorColor: ColorManager.black,
decoration: const InputDecoration(hintText: "Name"),
validator: (value) {
if (value!.isEmpty || value.length < 5) {
return "name can't be less than 5 chars";
}
return null;
},
),
gapH24,
Text(
"Category",
style: TextStyle(color: ColorManager.grey),
),
SizedBox(
width: deviceSize.width,
child: DropdownButtonFormField<String>(
// value: "Categories",
hint: const Padding(
padding: EdgeInsets.only(left: 10),
child: Text('No Category'),
),
items: <String>['No Category', 'Create Category']
.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) {},
),
),
gapH24,
const Text(
"Sold by",
style: TextStyle(color: Colors.black),
),
gapH24,
Row(
children: [
Checkbox(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5.0))), // Rounded Checkbox
value: each,
onChanged: (inputValue) {
setState(() {
each = !each;
});
},
),
gapW4,
const Text(
"Each",
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
gapH24,
Row(
children: [
Checkbox(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5.0))), // Rounded Checkbox
value: !each,
onChanged: (inputValue) {
setState(() {
each = !each;
});
},
),
gapW4,
const Text(
"Weight",
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
TextFormField(
controller: priceController,
decoration: InputDecoration(
hintText: "Price",
hintStyle: TextStyle(color: ColorManager.grey)),
validator: (value) {
if (value!.isEmpty) {
return "price can,t be empty";
}
return null;
},
),
gapH4,
Text(
"leave the field blank to indicate price upon sale",
style: TextStyle(color: ColorManager.grey),
),
gapH20,
Text(
"Cost",
style: TextStyle(color: ColorManager.grey),
),
TextFormField(
controller: costController,
decoration: InputDecoration(
hintText: "cost",
hintStyle: TextStyle(color: ColorManager.black)),
validator: (value) {
if (value!.isEmpty) {
return "cost can't be empty";
}
return null;
},
),
gapH20,
Text(
"SKU",
style: TextStyle(color: ColorManager.grey),
),
TextFormField(
controller: skuController,
decoration: InputDecoration(
hintText: "Sku",
hintStyle: TextStyle(color: ColorManager.black)),
validator: (value) {
if (value!.isEmpty) {
return "Sku can't be empty";
}
return null;
},
),
gapH30,
TextFormField(
controller: barcodeController,
decoration: InputDecoration(
hintText: "Barcode",
hintStyle: TextStyle(color: ColorManager.grey)),
validator: (value) {
if (value!.isEmpty) {
return "Barcode can't be empty";
}
return null;
},
),
gapH30,
// Divider(thickness: 1,color: ColorManager.black,),
Text(
"Inventory",
style: TextStyle(
color: ColorManager.green,
fontSize: 15,
fontWeight: FontWeight.bold),
),
// ListTile(
// title: Text("TrackStock",style: TextStyle(color: ColorManager.green,fontSize: 15,fontWeight: FontWeight.bold)),
// trailing: Switch(value: switchValue, onChanged: (bool value) {
// setState(() {
// switchValue=!switchValue;
// });
// },),
// ),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("TrackStock",
style: TextStyle(
color: ColorManager.grey,
fontSize: 15,
fontWeight: FontWeight.bold)),
Switch(
value: switchValue,
onChanged: (bool value) {
setState(() {
switchValue = !switchValue;
});
},
),
],
),
gapH10,
if (switchValue)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"in stock",
style:
TextStyle(color: ColorManager.grey, fontSize: 15),
),
TextFormField(
keyboardType: TextInputType.number,
controller: inStockController,
decoration: const InputDecoration(hintText: "0"),
validator: (value) {
if (value!.isEmpty) {
return "value can't be empty";
}
return null;
},
)
],
),
gapH20,
Text(
"Representation in POS",
style: TextStyle(
color: ColorManager.green,
fontSize: 15,
fontWeight: FontWeight.bold),
),
gapH15,
Row(
children: [
Checkbox(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5.0))), // Rounded Checkbox
value: isColor,
onChanged: (inputValue) {
setState(() {
if (!isColor) {
isColor = !isColor;
}
});
},
),
gapW4,
const Text(
"Color and Shape",
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
gapH10,
Row(
children: [
Checkbox(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5.0))), // Rounded Checkbox
value: !isColor,
onChanged: (inputValue) {
setState(() {
if (isColor) {
isColor = !isColor;
}
});
},
),
gapW4,
const Text(
"Image",
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
isColor
? GridView.builder(
physics:
const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
shrinkWrap: true, // You won't see infinite size error
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
),
itemCount: containers().length,
itemBuilder: (BuildContext context, int index) {
return containers()[index];
},
)
: Padding(
padding: const EdgeInsets.all(10),
child: Row(
children: [
Expanded(
flex: 1,
child: base64File == ""
? const Icon(Icons.person)
: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(5)),
child: Image.memory(
base64.decode(base64File)))),
gapW4,
Expanded(
flex: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextButton(
onPressed: () =>
pickImage(ImageSource.camera),
child: Row(
children: [
Icon(
Icons.camera_alt,
color: ColorManager.black,
),
gapW8,
Text(
"Take a photo",
style: TextStyle(
color: ColorManager.black,
),
)
],
),
),
const Divider(
thickness: 1,
color: Colors.grey,
),
TextButton(
onPressed: () =>
pickImage(ImageSource.gallery),
child: Row(
children: [
Icon(Icons.camera_alt,
color: ColorManager.black),
gapW8,
Text(
"Choose from gallery",
style: TextStyle(
color: ColorManager.black,
),
)
],
),
)
],
),
)
],
),
)
],
),
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.save,color: Colors.white,),
onPressed: () async {
bool isValid = _formKey.currentState!.validate();
if (isValid) {
FocusScope.of(context).unfocus();
ItemModel? item=await bloc.checkItem(nameController.text);
if(item!=null){
displayMessage("this item was inserted before", context);
}else{
int? res=await bloc.saveItem(ItemModel(
nameController.text,
priceController.text,
costController.text,
skuController.text,
barcodeController.text));
if(res!=null){
displayMessage("an item was inserted successfully", context);
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>const NewSales()), (route) => false);
}
}
}
},
),
);
}
),
);
}
}
this is the SaleCubit
class SalesCubit extends Cubit<SalesState> {
SalesCubit() : super(SalesInitial());
bool isSearch=false;
ItemDBHelper db=ItemDBHelper();
List<ItemModel> items=[];
List<ItemModel> filteredItems=[];
String bsResult='Unknown'; //barcode search result
void toggleSearch(){
isSearch=!isSearch;
emit(IsSearch());
}
void setBarcodeResult(String value){
bsResult=value;
emit(SearchDone());
}
void filterItems(String query){
// emit(Searching());
query.isEmpty?
filteredItems=items:
filteredItems=items.where((item) => item.name.toLowerCase().contains(query.toLowerCase())).toList();
emit(SearchDone());
}
Future<List<ItemModel>?> getAllItems()async{
try{
emit(IsLoading());
items=await db.getAllItems();
filteredItems=items;
print(items);
return items;
}finally{
emit(Loaded());
}
}
Future<void> deleteItem(String name)async{
await db.deleteItem(name);
emit(SearchDone());
}
}
this is the SalesState
part of 'sales_cubit.dart';
#immutable
abstract class SalesState {}
class SalesInitial extends SalesState {}
class IsSearch extends SalesState {}
class IsLoading extends SalesState {}
class Loaded extends SalesState {}
class Searching extends SalesState {}
class SearchDone extends SalesState {}

How can I create form modal with dropdown select in flutter

I am new to flutter and this is my first application. I have been trying to create a form modal with dropdown select would receive its data from the server. but for now I am using the values in array I created but it not setting the value after I select an item. I tried to add a setState() but is showing error. Please can someone help me?
Here is my code blow
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:erg_app/ProfilePage.dart';
void main() => runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: StockPage(),
)
);
class StockPage extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Inventory Data',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: StockInventory(),
);
}
}
class StockInventory extends StatefulWidget {
StockInventory({Key key}) : super(key: key); //Find out meaning
#override
_StockInventoryState createState() => _StockInventoryState();
}
class _StockInventoryState extends State<StockInventory> {
List<Products> products;
List<Products> selectedProducts;
bool sort;
#override
void initState() {
sort = false;
selectedProducts = [];
products = Products.getProducts();
super.initState();
}
onSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
products.sort((a, b) => a.name.compareTo(b.name));
} else {
products.sort((a, b) => b.name.compareTo(a.name));
}
}
}
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: new Center(child: new Text('Daily Stock Taking', textAlign: TextAlign.center)),
automaticallyImplyLeading: false,
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,),
body: Container(
child: ListView(
children: <Widget>[
Container(
margin: const EdgeInsets.only(right: 20, top: 20),
child: Align(
alignment: Alignment.bottomRight,
child: RaisedButton(
padding: EdgeInsets.fromLTRB(14, 10, 14, 10),
color: Colors.green,
child: Text("Take Inventory", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14), ),
onPressed: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfilePage()));
showSimpleCustomDialog(context);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
Container(
padding: EdgeInsets.only(top: 30, bottom: 30),
child: DataTable(
sortAscending: sort,
sortColumnIndex: 0,
columns: [
DataColumn(
label: Text("S/No", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Item", style: TextStyle(fontSize: 16)),
numeric: false,
onSort: (columnIndex, ascending) {
setState(() {
sort = !sort;
});
onSortColum(columnIndex, ascending);
}),
DataColumn(
label: Text("QtyInStock", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Unit", style: TextStyle(fontSize: 16)),
numeric: false,
),
],
rows: products
.map(
(product) => DataRow(
selected: selectedProducts.contains(product),
cells: [
DataCell(
Text(product.count),
onTap: () {
print('Selected ${product.count}');
},
),
DataCell(
Text(product.name),
onTap: () {
print('Selected ${product.name}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
]),
).toList(),
),
),
Container(
child: Center(
child: RaisedButton(
padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
color: Colors.green,
child: Text("Post Inventory", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14), ),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfilePage()));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
],
),
),
);
}
}
class Products {
String count;
String name;
String measuringunit;
String itemqty;
Products({this.count, this.name, this.itemqty, this.measuringunit});
static List<Products> getProducts() {
return <Products>[
Products(count:"1", name: "NPK Fertilizer", itemqty: "50", measuringunit: "bag",),
Products(count:"2", name: "Urea Fertilizer", itemqty: "560", measuringunit: "bag",),
Products(count:"3", name: "Spray", itemqty: "150", measuringunit: "bottles",),
];
}
}
void showSimpleCustomDialog(BuildContext context) {
String dropdownValue = 'SelectItem';
// TextEditingController _controller = TextEditingController(text: dropdownValue);
Dialog simpleDialog = Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: Container(
height: 300.0,
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top:20, bottom: 20, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(child:
Text(
'Item',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, ),
),
),
Container(width: 2,),
Container(
child:DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
// This set state is trowing an error
setState((){
dropdownValue = newValue;
});
},
items: <String>['Fertilizers', 'Bags', 'Spray', 'Equipments']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
})
.toList(),
),
),
],
)),
Padding(
padding: EdgeInsets.only(top:5, bottom: 5, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(child:
Text(
'Quantity',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, ),
),
),
Container(width: 2,),
Expanded(child: TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Quantity',
hintText: 'Enter Cost Quantity',
border:OutlineInputBorder(borderRadius: BorderRadius.circular(5.0))
),
)),
],
)),
Padding(
padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.blue,
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Add',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
SizedBox(
width: 20,
),
RaisedButton(
color: Colors.red,
onPressed: () {
Navigator.pop(context);
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => StockPage()));
},
child: Text(
'Cancel!',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
)
],
),
),
],
),
),
);
showDialog(context: context, builder: (BuildContext context) => simpleDialog);
}
// Dropdown Menu Class below
Maybe I think that using the Statefulbuilder for the dialog. So you can change the state there just check the sample example.
Change as per you needs :
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: StockPage(),
));
class StockPage extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Inventory Data',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: StockInventory(),
);
}
}
class StockInventory extends StatefulWidget {
StockInventory({Key key}) : super(key: key); //Find out meaning
#override
_StockInventoryState createState() => _StockInventoryState();
}
class _StockInventoryState extends State<StockInventory> {
List<Products> products;
List<Products> selectedProducts;
bool sort;
#override
void initState() {
super.initState();
sort = false;
selectedProducts = [];
products = Products.getProducts();
}
onSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
products.sort((a, b) => a.name.compareTo(b.name));
} else {
products.sort((a, b) => b.name.compareTo(a.name));
}
}
}
void showSimpleCustomDialog(BuildContext context) {
String dropdownValue ;
// TextEditingController _controller = TextEditingController(text: dropdownValue);
AlertDialog simpleDialog1 = AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
content: StatefulBuilder(
builder :(BuildContext context, StateSetter setState) {
return Container(
height: 300.0,
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding:
EdgeInsets.only(top: 20, bottom: 20, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(
child: Text(
'Item',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: 2,
),
Container(
child: DropdownButton<String>(
hint: Text('Enter value'),
value: dropdownValue,
onChanged: (String newValue) {
// This set state is trowing an error
setState(() {
dropdownValue = newValue;
});
},
items: <String>[
'Fertilizers',
'Bags',
'Spray',
'Equipments'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
),
),
],
)),
Padding(
padding:
EdgeInsets.only(top: 5, bottom: 5, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(
child: Text(
'Quantity',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: 2,
),
Expanded(
child: TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Quantity',
hintText: 'Enter Cost Quantity',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
)),
],
)),
Padding(
padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.blue,
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Add',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
SizedBox(
width: 20,
),
RaisedButton(
color: Colors.red,
onPressed: () {
Navigator.pop(context);
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => StockPage()));
},
child: Text(
'Cancel!',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
)
],
),
),
],
),
);
}
),
);
/* Dialog simpleDialog = Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child:
); */
showDialog(
context: context, builder: (BuildContext context) => simpleDialog1);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Center(
child: new Text('Daily Stock Taking', textAlign: TextAlign.center)),
automaticallyImplyLeading: false,
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
body: Container(
child: ListView(
children: <Widget>[
Container(
margin: const EdgeInsets.only(right: 20, top: 20),
child: Align(
alignment: Alignment.bottomRight,
child: RaisedButton(
padding: EdgeInsets.fromLTRB(14, 10, 14, 10),
color: Colors.green,
child: Text(
"Take Inventory",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
onPressed: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfilePage()));
showSimpleCustomDialog(context);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
Container(
padding: EdgeInsets.only(top: 30, bottom: 30),
child: DataTable(
sortAscending: sort,
sortColumnIndex: 0,
columns: [
DataColumn(
label: Text("S/No", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Item", style: TextStyle(fontSize: 16)),
numeric: false,
onSort: (columnIndex, ascending) {
setState(() {
sort = !sort;
});
onSortColum(columnIndex, ascending);
}),
DataColumn(
label: Text("QtyInStock", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Unit", style: TextStyle(fontSize: 16)),
numeric: false,
),
],
rows: products
.map(
(product) => DataRow(
selected: selectedProducts.contains(product),
cells: [
DataCell(
Text(product.count),
onTap: () {
print('Selected ${product.count}');
},
),
DataCell(
Text(product.name),
onTap: () {
print('Selected ${product.name}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
]),
)
.toList(),
),
),
Container(
child: Center(
child: RaisedButton(
padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
color: Colors.green,
child: Text(
"Post Inventory",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ProfilePage()));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
],
),
),
);
}
}
class Products {
String count;
String name;
String measuringunit;
String itemqty;
Products({this.count, this.name, this.itemqty, this.measuringunit});
static List<Products> getProducts() {
return <Products>[
Products(
count: "1",
name: "NPK Fertilizer",
itemqty: "50",
measuringunit: "bag",
),
Products(
count: "2",
name: "Urea Fertilizer",
itemqty: "560",
measuringunit: "bag",
),
Products(
count: "3",
name: "Spray",
itemqty: "150",
measuringunit: "bottles",
),
];
}
}
class ProfilePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container();
}
}
Just check the code.
Let me know if it works

Flutter: Carrying over data from one file to another

I have two files...Workout.dart and Submit.dart. In Workout.dart I have variables: name, sets, rep, pmg, and smg. The use will input things for the variables and then once they click submit, a new page will open displaying the data. However, I don't know how to carry over that data. I'm new to Flutter and Dart, Please help!
Workout.dart
import 'package:flutter/material.dart';
import 'package:gyminprogress/Submit.dart';
class This extends StatefulWidget{
#override
Workout createState() => Workout();
}
class Workout extends State<This> {
String name , sets , rep , pmg , smg ;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
hintText: 'Exercise Name'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
name = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Primary Muscle Group'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
pmg = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Secondary Muscle Group'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
smg = value;
});
},
),SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Reps'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
rep = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Sets'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
sets = value;
});
},
),
Expanded(
child: Container(
child: Column(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.cyan[200],
padding: EdgeInsets.symmetric(
horizontal: 80.0,
vertical: 20.0
,),
child: Text('Submit',style: TextStyle(
color: Colors.black,fontWeight: FontWeight.w200
),) ,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Submit (
)),
);
},
),
]
),]),)
)
]
)
),
),
);
}
}
Submit.dart
import 'package:flutter/material.dart';
import 'package:gyminprogress/Workout.dart';
class Submit extends StatefulWidget{
#override
Enter createState() => Enter();
}
class Enter extends State<Submit> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text('Exercise Name : ${Workout.name}',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Primary Muscle Group : ${Workout.pmg} ',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Secondary Muscle Group : ${Workout.smg} ',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Reps : ${Workout.rep}',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Sets : ${Workout.sets}',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
]
)
)
)
);
}
}
To pass data from one widget to another you have to do two things,
Create a constructor of widget having data which it will accept,
Pass that data while calling it from another widget.
here is the code which solves your problem:
workout.dart
import "package:flutter/material.dart";
import './submit.dart';
class Workout extends StatefulWidget {
#override
_WorkoutState createState() => _WorkoutState();
}
class _WorkoutState extends State<Workout> {
String name, sets, rep, pmg, smg;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Scaffold(
body: Column(children: <Widget>[
TextField(
decoration: InputDecoration(hintText: 'Exercise Name'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
name = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration:
InputDecoration(hintText: 'Primary Muscle Group'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
pmg = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration:
InputDecoration(hintText: 'Secondary Muscle Group'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
smg = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(hintText: 'Reps'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
rep = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(hintText: 'Sets'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
sets = value;
});
},
),
Expanded(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.cyan[200],
padding: EdgeInsets.symmetric(
horizontal: 80.0,
vertical: 20.0,
),
child: Text(
'Submit',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600),
),
onPressed: () {
//String name, sets, rep, pmg, smg;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Submit(
name: name,
sets: sets,
rep: rep,
pmg: pmg,
smg: smg,
),
),
);
},
),
]),
]),
))
]))),
),
),
),
);
}
}
submit.dart
import "package:flutter/material.dart";
class Submit extends StatelessWidget {
final String name, sets, rep, pmg, smg;
const Submit({
Key key,
this.name = "",
this.sets = "",
this.rep = "",
this.pmg = "",
this.smg = "",
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(children: <Widget>[
Text(
'Exercise Name : ${name}',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Primary Muscle Group : ${pmg} ',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Secondary Muscle Group : ${smg} ',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Reps : ${rep}',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Sets : ${sets}',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
]))));
}
}
Output:
New Updated code
Output:
You can pass data in the navigator.
class Workout extends ....> {
String name;
Person(this.name);
}
// Navigate to second screen with data
Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondScreenWithData(person: new Person("Vishal"))));
Then in the second screen
class SecondScreenWithData extends StatelessWidget {
// Declare a field that holds the Person data
final Person person;
// In the constructor, require a Person
SecondScreenWithData({Key key, #required this.person}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Second Screen With Data"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
// Display passed data from first screen
Text("name: ${person.name}"),
RaisedButton(
child: Text("Back to previous screen"),
onPressed: () {
// Navigate back to first screen when tapped!
Navigator.pop(context);
}
),
],
)
),
);
}