Flutter complains about undefined var, however i defined it - flutter

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,
...
...
)

Related

How can I display 'year' property only when I using scroll_date_picker in Flutter?

I ran into a snag while using the scroll_date_picker package. I succeeded in marking the scroll as shown in the figure below, but I want only the year to be displayed and scrolled, not all of the year, month, and day. How would I recommend changing _selectedDate in this case?
This is my code.
import 'package:flutter/material.dart';
import 'package:scroll_date_picker/scroll_date_picker.dart';
import 'package:shipda/constants.dart';
class BuiltYearChoice extends StatefulWidget {
const BuiltYearChoice({Key? key}) : super(key: key);
#override
State<BuiltYearChoice> createState() => _BuiltYearChoiceState();
}
class _BuiltYearChoiceState extends State<BuiltYearChoice> {
DateTime _selectedDate = DateTime.now();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: baseColor10,
elevation: 0,
leading: TextButton(
onPressed: () {},
child: Text('Reset'),
),
title: Text(
'Example',
style: titleMediumBase50(),
),
centerTitle: true,
actions: [
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(
Icons.close,
color: baseColor50,
),
),
],
),
body: Padding(
padding: const EdgeInsets.fromLTRB(48, 16, 48, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
Text(
'min',
// '최소진수년도',
style: TextStyle(
fontSize: bodyMedium,
fontFamily: 'regular',
color: Colors.grey.shade500,
),
),
marginHeight4,
Text(
'0000',
style: TextStyle(
fontSize: 32,
fontFamily: 'bold',
),
),
],
),
Column(
children: [
Text(''),
Text(
'~',
style: TextStyle(
fontSize: 32,
fontFamily: 'bold',
color: Colors.grey.shade400,
),
),
],
),
Column(
children: [
Text(
'max',
// '최대진수년도',
style: TextStyle(
fontSize: bodyMedium,
fontFamily: 'regular',
color: Colors.grey.shade500,
),
),
marginHeight4,
Text(
'0000',
style: TextStyle(
fontSize: 32,
fontFamily: 'bold',
),
),
],
),
],
),
SizedBox(
height: 300,
child: ScrollDatePicker(
locale: Locale('ko'),
selectedDate: _selectedDate,
onDateTimeChanged: (DateTime value) {
setState(() {
_selectedDate = value;
});
}),
)
],
),
),
);
}
}
You can make your CustomPicker, something like this:
import 'package:flutter/material.dart';
class CustomPicker extends StatelessWidget {
final List<DateTime> list;
const CustomPicker(this.list, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// define item height
double itemHeight = 30;
var middleIndex = (list.length / 2).floor(); // index of the middle item
var scrollController = ScrollController(
// if you want middle item to be pre-selected
initialScrollOffset: middleIndex * itemHeight,
);
int numberOfItemsToBeVisible = 5;
double pickerHeight = itemHeight * numberOfItemsToBeVisible;
// or you can pass index of the item you want to be visible
var selectedItem = ValueNotifier(list[middleIndex]);
// changing selected item on scroll
scrollController.addListener(() {
selectedItem.value = list[(scrollController.offset / itemHeight).round()];
});
return Column(
children: [
Stack(
children: [
Positioned.fill(
child: Center(
child: Container(
height: itemHeight,
width: MediaQuery.of(context).size.width,
decoration: ShapeDecoration(
color: Colors.grey.shade300,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
),
),
),
),
// picker
SizedBox(
height: pickerHeight,
child: ListWheelScrollView(
diameterRatio: 1.2,
itemExtent: itemHeight,
controller: scrollController,
children: list
.map(
(element) => Align(
alignment: Alignment.center,
child: Text('${element.year}'),
),
)
.toList(),
),
),
],
),
// selected item
ValueListenableBuilder(
valueListenable: selectedItem,
builder: (context, DateTime value, _) =>
Text('selected year: ${value.year}'),
),
],
);
}
}
Then you can use it like this:
SizedBox(
height: 300,
child: CustomPicker(
List.generate(21, (index) => DateTime(2000 + index)),
),
)
The result is:

stack overflow error:The following StackOverflowError was thrown building OnboardingView(dirty): Stack Overflow

there is also a terminal output....
I have this problem after copying and pasting a code from out side the project .
I think it had to do with routes or the GetX packege because I dont know how to use correctly so it may be the problem. and there is also the routes code i have included it here and I think it may be something there and not forgetting the cntrollers code ..I have also included it here
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import '../controllers/onboarding_controller.dart';
class OnboardingView extends GetView<OnboardingController> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
PageView.builder(
controller: controller.onboardingController.pageController,
onPageChanged: controller.onboardingController.selectedPageIndex,
itemCount: controller.onboardingController.onboardingPages.length,
itemBuilder: (context, index) {
return Stack(
children: [
Image.asset(
controller.onboardingController.onboardingPages[index]
.imageAsset,
fit: BoxFit.cover,
),
Align(
alignment: const AlignmentDirectional(0, 0.1),
child: Text(
controller.onboardingController.onboardingPages[index]
.title,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 57,
),
)),
Align(
alignment: const AlignmentDirectional(0, 0.40),
child: Text(
controller.onboardingController.onboardingPages[index]
.description,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
fontFamily: 'Inter',
fontSize: 18,
),
),
),
],
);
}),
Align(
alignment: const AlignmentDirectional(0, 0.55),
child: SmoothPageIndicator(
effect: ExpandingDotsEffect(),
controller: controller.onboardingController.pageController,
count: 3)),
// Align(
// alignment: const AlignmentDirectional(0, 0.55),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: List.generate(
// _controller.onboardingPages.length,
// (index) => Obx(() {
// return Container(
// margin: const EdgeInsets.all(4),
// width: 12,
// height: 12,
// decoration: BoxDecoration(
// color: _controller.selectedPageIndex.value == index
// ? Colors.white
// : Colors.grey,
// shape: BoxShape.circle,
// ),
// );
// })),
// ),
// ),
Align(
//
alignment: const AlignmentDirectional(0, 0.75),
child: Obx(() {
return controller.onboardingController.isLastPage
? ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
fixedSize: const Size(350, 45)),
onPressed: () {},
// onPressed: () => Get.to(LogInPage()),
child: const Text(
"LogIn",
style: TextStyle(fontSize: 20, letterSpacing: 2),
))
: ElevatedButton(
onPressed: controller.onboardingController.forwardAction,
style: ElevatedButton.styleFrom(
side: const BorderSide(color: Colors.white),
backgroundColor: Colors.transparent,
fixedSize: const Size(350, 45)),
child: const Text(
'Next',
style: TextStyle(fontSize: 20, letterSpacing: 2),
),
);
}),
),
Align(
//
alignment: const AlignmentDirectional(0, 0.90),
child: Obx(() {
return controller.onboardingController.isLastPage
? ElevatedButton(
style: ElevatedButton.styleFrom(
side: const BorderSide(color: Colors.white),
backgroundColor: Colors.transparent,
fixedSize: const Size(350, 45)),
onPressed: () {
// Get.to(SignUpPage());
},
child: Text("create an account"))
: ElevatedButton(
style: ElevatedButton.styleFrom(
side: const BorderSide(color: Colors.white),
backgroundColor: Colors.transparent,
fixedSize: const Size(350, 45)),
onPressed: () => controller
.onboardingController.pageController
.jumpToPage(2),
child: Text(
'Skip',
style: const TextStyle(fontSize: 20, letterSpacing: 1),
),
);
}),
),
Align(
alignment: const AlignmentDirectional(0, 0.30),
child: Obx(() {
return Text(
controller.onboardingController.isLastPage
? 'The only shopping \nApp you need '
: '',
style: const TextStyle(
color: Colors.white,
fontSize: 34,
fontWeight: FontWeight.w600),
);
}),
),
],
),
);
}
}
import 'package:azyaa/app/data/onboarding_data.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class OnboardingController extends GetxController {
final onboardingController = OnboardingController();
var selectedPageIndex = 0.obs;
bool get isLastPage => selectedPageIndex.value == onboardingPages.length - 1;
var pageController = PageController();
forwardAction() {
if (isLastPage) {
//do this
} else
pageController.nextPage(duration: 300.milliseconds, curve: Curves.ease);
}
List<OnboardingInfo> onboardingPages = [
OnboardingInfo("assets/1.png", "Shop better,\nlook good.\n",
"Buy pre-loved Gucci, Louis Vuitton,\nOff-White... 12,000 brands up to 70%\noff retail price, all great for the planet."),
OnboardingInfo("assets/2.png", "Delivered\nto your spot",
"Buy pre-loved Gucci, Louis Vuitton,\nOff-White... 12,000 brands up to 70%\noff retail price, all great for the planet."),
OnboardingInfo("assets/3.png", "", ""),
];
#override
void onInit() {
super.onInit();
}
#override
void onReady() {
super.onReady();
}
#override
void onClose() {}
}
part of 'app_pages.dart';
// DO NOT EDIT. This is code generated via package:get_cli/get_cli.dart
abstract class Routes {
Routes._();
static const HOME = _Paths.HOME;
static const ONBOARDING = _Paths.ONBOARDING;
}
abstract class _Paths {
_Paths._();
static const HOME = '/home';
static const ONBOARDING = '/onboarding';
}
import 'package:get/get.dart';
import '../modules/home/bindings/home_binding.dart';
import '../modules/home/bindings/home_binding.dart';
import '../modules/home/views/home_view.dart';
import '../modules/home/views/home_view.dart';
import '../modules/onboarding/bindings/onboarding_binding.dart';
import '../modules/onboarding/views/onboarding_view.dart';
part 'app_routes.dart';
class AppPages {
AppPages._();
static const INITIAL = Routes.ONBOARDING;
static final routes = [
GetPage(
name: _Paths.HOME,
page: () => HomeView(),
binding: HomeBinding(),
children: [
GetPage(
name: _Paths.HOME,
page: () => HomeView(),
binding: HomeBinding(),
),
],
),
GetPage(
name: _Paths.ONBOARDING,
page: () => OnboardingView(),
binding: OnboardingBinding(),
),
];
}
``
I am not sure but think the error has to do with routes ....I dont actually know

Navigator.push it doesn't work how can i fix it?

I created 3 files, in the second file I put it inside the Elevatedbutton, but when I press the button I don't go to the other pagethe first it has this code :
import 'package:flutter/material.dart';
import 'Firstpage.dart';
void main (){
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstPage(),
);
}
}
in the second file i have :
import 'package:flutter/material.dart';
import 'planetspage.dart';
class FirstPage extends StatefulWidget {
const FirstPage({Key? key}) : super(key: key);
#override
State<FirstPage> createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
var lang = "en";
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Stack(
children: [
Image.asset(
'images/firstwal.jpg',
width: double.infinity,
fit: BoxFit.cover,
),
Container(
padding: const EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const Text(
'Explore space',
style: TextStyle(
fontSize: 35,
color: Colors.white,
fontWeight: FontWeight.w500),
),
const SizedBox(
height: 10,
),
const Text(
'a system of millions or billions of stars, together with gas and dust, held together by gravitational attraction.',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
color: Colors.white),
),
const SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(30)),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 40),
color: Colors.white,
child: DropdownButton(
items: [
"en",
"ar",
]
.map((e) => DropdownMenuItem(
child: Text(e),
value: e,
))
.toList(),
onChanged: (val) {
setState(() {
lang = val.toString();
});
},
value: lang,
style:
const TextStyle(color: Colors.black87, fontSize: 20),
iconEnabledColor: Colors.black87,
)),
),
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(30)),
child: ElevatedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> const enPlanetspage()));
},
style: ElevatedButton.styleFrom(
primary: Colors.deepPurple),
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
child: Row(
children: const [
Text(
'Next',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
Icon(Icons.navigate_next_outlined),
],
),
)),
),
],
),
],
),
),
],
),
),
);
}
}
when i press the button Navigator.push doesn't work how can i fix it?
I created 3 files, in the second file I put it inside the Elevatedbutton, but when I press the button I don't go to the other pagethe first it has this code :
Try using:
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context)=> const enPlanetspage()));
Check if your image files are mentioned in the pubsec.

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

Get Time Picker's Value within a Widget

I am trying to get the DateTime that is chosen from the user and save it within an object.
This is implemented within the following construction:
return Scaffold(
appBar: AppBar(
title: Text('Add/Edit Shift'),
),
body: Container(
color: Colors.white,
margin: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 40.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(5.0)),
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
child: Text(
'Scheduling Date: ${_dateformat.format(widget.shiftDate)}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
color: Colors.teal,
),
),
),
// fixme: how to get the clicked value from the user?
// the value has to get saved within an object that will be returned
MyTimePicker(_startOfShift),
MyTimePicker(_endOfShift),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Text(
"Submit",
style: TextStyle(
color: Colors.teal,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
onPressed: () {
// todo: return the shift to the calendar
// print(MyTimePicker(_startOfShift).chosenTime);
Navigator.pop(
context,
);
},
)
],
),
),
),
),
);
And this is how it looks like:
The MyTimePickerClass is created as a separate Dart file. Within the MyTimePicker class, I construct a RaisedButton labeled as Start and End where the user is capable to choose the wanting time.
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class MyTimePicker extends StatefulWidget {
String typeOfShift;
MyTimePicker(this.typeOfShift);
#override
_MyTimePickerState createState() => _MyTimePickerState();
}
class _MyTimePickerState extends State<MyTimePicker> {
#override
Widget build(BuildContext context) {
return RaisedButton(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
elevation: 4.0,
onPressed: () {
DateTime test = _MyDatePicker(context);
widget.typeOfShift = test.toString();
setState(() {});
},
child: Container(
alignment: Alignment.center,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Container(
child: Row(
children: <Widget>[
Icon(
Icons.access_time,
size: 18.0,
color: Colors.teal,
),
Text(
" ${widget.typeOfShift}",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
)
],
),
Text(
" Change",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
),
color: Colors.white,
);
}
DateTime _MyDatePicker(BuildContext context) {
DateTime _myDateTime;
DatePicker.showTimePicker(context,
showSecondsColumn: false,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true, onConfirm: (time) {
// _chosenTime = time;
_myDateTime = time;
print('confirm $time');
// widget.typeOfShift = '${time.hour} : ${time.minute}';
setState(() {});
}, currentTime: DateTime.now(), locale: LocaleType.de);
return _myDateTime;
}
}
Then the time is displayed in the UI. How could I access this time??
You can copy paste run full code below
You can define two MyTimePicker and use it
When onPressed , you can use startPicker.typeOfShift to get String
MyTimePicker startPicker = MyTimePicker("Start");
MyTimePicker endPicker = MyTimePicker("End");
...
startPicker,
endPicker,
RaisedButton(
...
onPressed: () {
print(startPicker.typeOfShift);
print(endPicker.typeOfShift);
output
I/flutter (31204): 1 : 23
I/flutter (31204): 1 : 25
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class MyTimePicker extends StatefulWidget {
String typeOfShift;
MyTimePicker(this.typeOfShift);
#override
_MyTimePickerState createState() => _MyTimePickerState();
}
class _MyTimePickerState extends State<MyTimePicker> {
#override
Widget build(BuildContext context) {
return RaisedButton(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
elevation: 4.0,
onPressed: () {
DateTime test = _MyDatePicker(context);
widget.typeOfShift = test.toString();
setState(() {});
},
child: Container(
alignment: Alignment.center,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Container(
child: Row(
children: <Widget>[
Icon(
Icons.access_time,
size: 18.0,
color: Colors.teal,
),
Text(
" ${widget.typeOfShift}",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
)
],
),
Text(
" Change",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
),
color: Colors.white,
);
}
DateTime _MyDatePicker(BuildContext context) {
DateTime _myDateTime;
DatePicker.showTimePicker(context,
showSecondsColumn: false,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true, onConfirm: (time) {
// _chosenTime = time;
_myDateTime = time;
print('confirm $time');
widget.typeOfShift = '${time.hour} : ${time.minute}';
setState(() {});
}, currentTime: DateTime.now(), locale: LocaleType.de);
return _myDateTime;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
MyTimePicker startPicker = MyTimePicker("Start");
MyTimePicker endPicker = MyTimePicker("End");
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add/Edit Shift'),
),
body: Container(
color: Colors.white,
margin: EdgeInsets.all(16.0),
child: Form(
//key: _formKey,
child: SingleChildScrollView(
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 40.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(5.0)),
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
child: Text(
'Scheduling Date: ',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 19.0,
color: Colors.teal,
),
),
),
// fixme: how to get the clicked value from the user?
// the value has to get saved within an object that will be returned
startPicker,
endPicker,
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Text(
"Submit",
style: TextStyle(
color: Colors.teal,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
onPressed: () {
print(startPicker.typeOfShift);
print(endPicker.typeOfShift);
// todo: return the shift to the calendar
// print(MyTimePicker(_startOfShift).chosenTime);
Navigator.pop(
context,
);
},
)
],
),
),
),
),
);
}
}