In this, when the uniq_id of the button and the uniq_id of the data table match, only then the data of the user of that uniq_id will show.
But this error is coming before the data shows.
Did show the data for one time but after this error came, for both the page
This is my p_team.dart
This is the part of the button that is coming from the Api.
import 'package:flutter/material.dart';
import 'package:practice/listPost/p_team_list.dart';
import 'package:practice/post/post.dart';
import 'package:practice/post/services.dart';
class PTeam extends StatefulWidget {
#override
_PTeamState createState() => _PTeamState();
}
class _PTeamState extends State<PTeam> with SingleTickerProviderStateMixin {
List<Post>? posts;
#override
void initState() {
Services().getPosts().then((list) {
(() {
posts = list;
print(posts);
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
margin: const EdgeInsets.all(20.0),
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(width: 2, color: Colors.greenAccent)),
child: Row(
children: [
Text(
"Total Income:",
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic),
),
SizedBox(
width: 10.0,
),
Text(
"Rs.2000",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic),
),
],
),
),
SizedBox(
height: 20.0,
),
Flexible(
child: Container(
child: GridView.count(
childAspectRatio: 1.0,
padding: EdgeInsets.only(left: 16, right: 16),
crossAxisCount: 2,
crossAxisSpacing: 18,
mainAxisSpacing: 18,
children: List.generate(
posts!.length,
(index) => GestureDetector(
onTap: () {
print(posts![index].teamUniqId);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PTeamList(
teamUniqId: posts![index].teamUniqId,
teamType: posts![index].teamType,
)),
);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xff00ffaa),
borderRadius: BorderRadius.circular(10)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(posts![index].teamType,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600)),
),
],
),
),
),
),
),
),
),
],
),
);
}
}
This is my button api's data for p_team.dart.
[{"teamType":"direct team","team_name":"platinum","team_number":"234","team_uniq_id":"1","team_last_update":"10-may-2021"},{"teamType":"left team","team_name":"gold","team_number":"356","team_uniq_id":"2","team_last_update":"10-may-2021"},{"teamType":"right team","team_name":"silver","team_number":"876","team_uniq_id":"3","team_last_update":"10-may-2021"}]
this is my p_team_list.dart.
In this, when the uniq_id of the button and the uniq_id of the data table match, only then the data of the user of that uniq_id will show.
import 'package:flutter/material.dart';
import 'package:practice/listPost/post_list.dart';
import 'package:practice/listPost/services.dart';
class PTeamList extends StatefulWidget {
final teamUniqId;
final teamType;
const PTeamList({Key? key, this.teamUniqId, this.teamType}) : super(key: key);
#override
_PTeamListState createState() => _PTeamListState();
}
class _PTeamListState extends State<PTeamList> {
List<Post>? posts;
#override
void initState() {
Services().getPosts().then((list) {
setState(() {
posts = list;
print("za$posts");
});
});
}
#override
Widget build(BuildContext context) {
// if(widget.teamUniqId==posts.)
return Scaffold(
body:
// Text(widget.teamType),
Flexible(
child: Container(
child: Stack(
children: List.generate(posts!.length, (index) {
if (posts!.length == null) {
print(posts![index].user);
return Center(child: CircularProgressIndicator());
}
else if (widget.teamUniqId == posts![index].teamUniqId) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
// Data table widget in not scrollable so we have to wrap it in a scroll view when we have a large data set..
child: SingleChildScrollView(
child: DataTable(
columns: [
// DataColumn(
// label: Text('Verified'),
// tooltip: 'represents if user is verified.'),
DataColumn(
label: Text('S No'),
tooltip: 'represents first S no of the user'),
DataColumn(
label: Text('Sponsor ID'),
tooltip: 'represents Sponsor ID of the user'),
DataColumn(
label: Text('User ID'),
tooltip: 'represents User ID of the user'),
DataColumn(
label: Text('Name'),
tooltip: 'represents Name of the user'),
DataColumn(
label: Text('Mobile'),
tooltip: 'represents Mobile of the user'),
DataColumn(
label: Text('Date'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('a'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('b'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('c'),
tooltip: 'represents Date of the user'),
DataColumn(
label: Text('d'),
tooltip: 'represents Date of the user'),
],
rows: posts![index]
.user
.map((data) =>
DataRow(
cells: [
// I want to display a green color icon when user is verified and red when unverified
DataCell(Text(data.userName)),
DataCell(Text(data.userMotherName)),
DataCell(Text(data.userAddress)),
DataCell(Text(data.userSponsorId)),
DataCell(Text(data.sponsorId)),
DataCell(Text(data.email)),
DataCell(Text(data.city)),
DataCell(Text(data.state)),
DataCell(Text(data.userMobile)),
DataCell(Text(data.dob)),
]))
.toList(),
),
),
);
}
return Text("");
}),
),
),
),
);
}
}
This is my data table api's data for p_team.dart.
[{"teamType":"direct Team","team_uniq_id":"1","user":[{"user_name":"deepak","user_mother_name":"Accomodation","user_address":"varanasi","user_mobile":"5678989","user_sponsor_id":"123456","sponsor_id":"3456","email":"abc#gmai.com","city":"varanasi","state":"India","dob":"12-5-1996"},{"user_name":"deepak","user_mother_name":"Accomodation","user_address":"varanasi","user_mobile":"5678989","user_sponsor_id":"123456","sponsor_id":"3456","email":"abc#gmai.com","city":"varanasi","state":"India","dob":"12-5-1996"},{"user_name":"deepak","user_mother_name":"Accomodation","user_address":"varanasi","user_mobile":"5678989","user_sponsor_id":"123456","sponsor_id":"3456","email":"abc#gmai.com","city":"varanasi","state":"India","dob":"12-5-1996"}]},{"teamType":"left Team","team_uniq_id":"2","user":[{"user_name":"Ashu","user_mother_name":"manju","user_address":"Mirzapur","user_mobile":"222222","user_sponsor_id":"123456","sponsor_id":"3456","email":"abc#gmai.com","city":"varanasi","state":"India","dob":"12-5-1996"},{"user_name":"Ashutodh","user_mother_name":"manju1","user_address":"Mirzapur1","user_mobile":"2222221","user_sponsor_id":"1234561","sponsor_id":"34561","email":"abc#gmai.com1","city":"varanasi1","state":"India1","dob":"12-5-19961"}]},{"teamType":"Right Team","team_uniq_id":"3","user":[{"user_name":"tosh","user_mother_name":"snju","user_address":"Allahabad","user_mobile":"44444444","user_sponsor_id":"333456","sponsor_id":"6666666","email":"jkl#gmai.com","city":"lucknow","state":"India","dob":"15-3-1956"}]},{"teamType":"Total Team","team_uniq_id":"4","user":[{"user_name":"tosh","user_mother_name":"snju","user_address":"Allahabad","user_mobile":"44444444","user_sponsor_id":"333456","sponsor_id":"6666666","email":"jkl#gmai.com","city":"lucknow","state":"India","dob":"15-3-1956"},{"user_name":"deepak","user_mother_name":"Accomodation","user_address":"varanasi","user_mobile":"5678989","user_sponsor_id":"123456","sponsor_id":"3456","email":"abc#gmai.com","city":"varanasi","state":"India","dob":"12-5-1996"},{"user_name":"deepak","user_mother_name":"Accomodation","user_address":"varanasi","user_mobile":"5678989","user_sponsor_id":"123456","sponsor_id":"3456","email":"abc#gmai.com","city":"varanasi","state":"India","dob":"12-5-1996"},{"user_name":"tosh","user_mother_name":"snju","user_address":"Allahabad","user_mobile":"44444444","user_sponsor_id":"333456","sponsor_id":"6666666","email":"jkl#gmai.com","city":"lucknow","state":"India","dob":"15-3-1956"}]}]
The cause of this issue is that you're using a bang ! operator on a null value. This indicates that the Object can't be null, and throws an error if so.
You can either add a null check at the start or if the value can be null, it's best to use a nullable ? operator instead.
The error can be easily demonstrated with
int? foo; // nullable var
debugPrint('${foo!}'); // with the ! operator, Flutter expects the value to never be null
Related
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:
I'm trying to search item from ListView but I can't seem to find a way. What I want is when I type in the contact name from my contact list, then the specific contact appears on the page.
Here is my search code:
Row(
children: [
Icon(
Icons.search,
color: Color(0xff99999B),
size: 20,
),
Expanded(
child: TextField(
cursorColor: Colors.grey,
onChanged: (value) {
setState(() {
contactList = contactList.where((element) => element.contains(value)).toList();
});
},
decoration: InputDecoration(
hintText: 'Search contact...',
hintStyle: TextStyle(
color: Color(0xff99999B),
fontSize: 12
...
And my ListView code:
Container(
child: ListView.builder(
itemCount: contactList.length,
itemBuilder:(BuildContext context,index)=>
Column(
children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 250
),
child: Text(contactList[index].userName!,
...
Is there any solutions?
var contactList = ["asi", "adi", "java", "c++", "Kotlin", "Dart", "Flutter"];
var contactList2 = [];
consider create two list keep the original list and manage the secondlist for filtering .look below example
Your widget like
Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.add),
),
],
),
body: Column(
children: [
Container(
height: 50,
child: Row(children: [
Icon(
Icons.search,
color: Color(0xff99999B),
size: 20,
),
Expanded(
child: TextField(
cursorColor: Colors.grey,
onChanged: (value) {
setState(() {
contactList2 = contactList
.where((element) => element
.toLowerCase()
.contains(value.toLowerCase()))
.toList();
});
},
decoration: InputDecoration(
hintText: 'Search contact...',
hintStyle: TextStyle(
color: Color(0xff99999B), fontSize: 12))))
]),
),
Flexible(
child: ListView.builder(
itemCount: contactList2.length,
itemBuilder: (BuildContext context, index) => ListTile(
title: Text(
contactList2[index],
style:
TextStyle(color: Color(0xff99999B), fontSize: 25),
),
)),
)
],
),
);
SAmpleCode DArtpad live code check here
import 'package:flutter/material.dart';
//import 'package:pucon/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Parent(),
);
}
}
class Parent extends StatefulWidget {
#override
State<Parent> createState() => _ParentState();
}
var contactList = ["Asif", "adi", "java", "c++", "Kotlin", "Dart", "Flutter"];
var contactList2 = [];
class _ParentState extends State<Parent> {
Widget build(context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.add),
),
],
),
body: Column(
children: [
Container(
height: 50,
child: Row(children: [
Icon(
Icons.search,
color: Color(0xff99999B),
size: 20,
),
Expanded(
child: TextField(
cursorColor: Colors.grey,
onChanged: (value) {
setState(() {
contactList2 = contactList
.where((element) => element
.toLowerCase()
.contains(value.toLowerCase()))
.toList();
});
},
decoration: InputDecoration(
hintText: 'Search contact...',
hintStyle: TextStyle(
color: Color(0xff99999B), fontSize: 12))))
]),
),
Flexible(
child: ListView.builder(
itemCount: contactList2.length,
itemBuilder: (BuildContext context, index) => ListTile(
title: Text(
contactList2[index],
style:
TextStyle(color: Color(0xff99999B), fontSize: 25),
),
)),
)
],
),
);
}
}
I am stuck in creating query for the selected items and show selected data on other page. So help me to create query or condition. when I press floating action button then I want to get selected items data on other page.
Here is Main File code:
class MenuPage extends StatefulWidget {
const MenuPage({Key? key}) : super(key: key);
#override
_MenuPageState createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage> {
DatabaseReference db = FirebaseDatabase.instance.reference();
User? curUser = FirebaseAuth.instance.currentUser;
int? len;
List<GetData>? data;
late List<bool>? avail = List.generate(
len!,
(index) => false,
);
late List<TextEditingController>? qty = List.generate(
len!,
(index) => TextEditingController(),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Today's Menu"),
centerTitle: true,
backgroundColor: Colors.deepOrange,
),
body: StreamBuilder<List<GetData>>(
stream: DataStreamPublisher("Juices").getMenuStream(),
builder: (context, snapshot) {
if (snapshot.hasData) {
data = snapshot.data;
len = data!.length;
return SafeArea(
child: SingleChildScrollView(
child: Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: double.infinity,
child: DataTable2(
showBottomBorder: true,
headingRowHeight: 40,
showCheckboxColumn: true,
sortAscending: true,
columnSpacing: 5,
dataRowHeight: 60,
dividerThickness: 2,
bottomMargin: 20.0,
checkboxHorizontalMargin: 5,
columns: [
DataColumn2(
size: ColumnSize.L,
label: Center(
child: Text(
"Item Name",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
),
DataColumn2(
size: ColumnSize.S,
label: Center(
child: Text(
"Price",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
),
DataColumn2(
size: ColumnSize.L,
label: Center(
child: Text(
"Quantity",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
),
],
rows: List<DataRow>.generate(
data!.length,
(index) => DataRow2(
selected: avail![index],
onSelectChanged: (bool? value) {
setState(() {
avail![index] = value!;
});
},
color: MaterialStateProperty.resolveWith<Color?>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return Theme.of(context)
.colorScheme
.primary
.withOpacity(0.08);
}
return null;
},
),
cells: [
DataCell(
Text(
data![index].Juice_Name,
),
),
DataCell(
Center(
child: Text(
data![index].Price,
),
),
),
DataCell(
Center(
child: IncDecButton(
Qty: qty![index],
),
),
),
],
),
),
),
),
],
),
),
),
);
} else if (snapshot.hasError) {
return Center(
child: Text(
'Add Item in Menu.',
style: TextStyle(
fontSize: 18,
),
),
);
}
return Center(
child: const CircularProgressIndicator(),
);
},
),
floatingActionButton: FloatingActionButton(
tooltip: "Proceed to Bill",
onPressed: () {
// When I pressed floating button I want only selected items data
},
child: Text("ADD"),
),
);
}
}
This is stream of GetDataPublisher
This code get data from firebase.
class DataStreamPublisher {
final String dbChild;
DatabaseReference database = FirebaseDatabase.instance.reference();
User? curUser = FirebaseAuth.instance.currentUser;
DataStreamPublisher(this.dbChild);
Stream<List<GetData>> getMenuStream() {
final dataStream = database.child(curUser!.uid).child(dbChild)
.orderByChild("Available").equalTo(true).onValue;
final streamToPublish = dataStream.map((event) {
final dataMap = Map<String, dynamic>.from(event.snapshot.value);
final dataList = dataMap.entries.map((e) {
return GetData.fromRTDB(Map<String, dynamic>.from(e.value));
}).toList();
return dataList;
});
return streamToPublish;
}
}
This is get data class
class GetData {
String Juice_Name;
String Price;
GetData({
required this.Juice_Name,
required this.Price,
});
factory GetData.fromRTDB(Map<String, dynamic> data) {
return GetData(
Juice_Name: data['Juice_Name'] ?? 'Enter Juice Name',
Price: data['Price'] ?? 'Enter Price',
);
}
}
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
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);
}
),
],
)
),
);
}