Resetting Radio List in Flutter - flutter

I am still a novice with flutter and I am working on a quiz app right now
In the radio button list whenever the app goes to next question the radio buttons are not getting reset and I will be grateful if someone can guide me on how I can reset radio button on calling next question function
Pseudocode
class _QuizPageState extends State<QuizPage> {
List<dynamic> myQuestion;
_QuizPageState(this.myQuestion);
int i = 0;
int count = 0;
int selectedRadioTile;
int marks = 0;
var selected;
Widget choiceButton(String k, int value) {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10,
),
child: RadioListTile(
value: value,
groupValue: selectedRadioTile,
title: Container(
child: Text(myQuestion[i][k] ?? "None"),
),
onChanged: (val) {
setSelectedRadioTile(val);
selected = val;
},
activeColor: Colors.green,
selected: true,
),
);
}
void initState() {
selectedRadioTile = 0;
super.initState();
}
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
void checkAnswer() {
var e = int.parse(myQuestion[i]["Answer"]);
if (e == selected) {
marks = marks + 1;
} else {
print("wrong");
}
nextquestion();
}
void nextquestion() {
setState(() {
if (count < 9) {
i = randomBetween(0, myQuestion.length);
} else {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => resultpage(marks: marks),
));
}
});
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Alert",
),
content: Text("You Can't Go Back At This Stage."),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Ok',
),
)
],
));
},
child: Scaffold(
appBar: AppBar(
elevation: 30.0,
title: Center(
child: Text(
'Quiz',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontFamily: "Quando",
fontWeight: FontWeight.bold,
),
),
),
backgroundColor: Colors.amber[800],
),
body: LayoutBuilder(
builder: (context, constraint) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraint.maxHeight),
child: IntrinsicHeight(
child: Column(
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Center(
child: Container(
padding: EdgeInsets.only(top: 20, left: 10),
child: Text(
myQuestion[i]["Question"] ?? "None",
style: TextStyle(
fontSize: 15.0,
fontFamily: "Quando",
fontWeight: FontWeight.bold,
),
),
),
),
SizedBox(
height: 20,
),
Expanded(
child: AspectRatio(
aspectRatio: 16 / 11,
child: ClipRect(
child: SizedBox(
height: 50,
child: PhotoView(
imageProvider: AssetImage(
myQuestion[i]["Image"] ?? "None"),
minScale:
PhotoViewComputedScale.contained *
0.5,
maxScale:
PhotoViewComputedScale.covered * 2,
initialScale: 0.6,
backgroundDecoration: BoxDecoration(
color: Theme.of(context).canvasColor,
),
),
),
),
),
),
Text(
"To adjust the image double Tap",
style: TextStyle(
fontFamily: "Quando",
color: Colors.black26,
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
SizedBox(
height: 10,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
choiceButton("option1", 1),
choiceButton("option2", 2),
choiceButton("option3", 3),
choiceButton("option4", 4),
],
),
),
Expanded(
flex: 0,
child: RaisedButton(
splashColor: Colors.blueAccent,
color: Colors.blueAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
onPressed: () {
checkAnswer();
count = count + 1;
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Explaination",
),
content: Text(
myQuestion[i]["Explanation"] ?? "None",
style: TextStyle(
fontSize: 15.0,
fontFamily: "Quando",
),
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Ok',
),
)
],
));
},
child: Text(
'Submit',
),
),
),
SizedBox(
height: 40,
)
],
),
),
),
);
},
),
),
);
}
}

You could just set selectedRadioTile to 0 in nextQuestion:
void nextquestion() {
setState(() {
selectedRadioTile = 0;
if (count < 9) {
i = randomBetween(0, myQuestion.length);
} else {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => resultpage(marks: marks),
));
}
});
}

Related

How can I make the on pressed function lead to a webpage?

I have this bit of code and I want the onPressed function for all options on my menu to open a url. I'm not entirely familar with this so I need a little help.
Here is my code below
class NewProfile extends StatefulWidget {
const NewProfile({Key key, this.scaffoldKey}) : super(key: key);
final GlobalKey<ScaffoldState> scaffoldKey;
_NewProfileState createState() => _NewProfileState();
}
class _NewProfileState extends State<NewProfile> {
Widget _menuHeader() {
final state = context.watch<AuthState>();
if (state.userModel == null) {
return ConstrainedBox(
constraints: BoxConstraints(minWidth: 200, minHeight: 100),
child: Center(
child: Text(
'Login to continue',
style: TextStyles.onPrimaryTitleText,
),
),
).ripple(() {
_logOut();
// Navigator.of(context).pushNamed('/signIn');
});
} else {
return Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 120,
width: 120,
margin: EdgeInsets.only(left: 17, top: 10),
decoration: BoxDecoration(
border: Border.all(color: kPrimaryColor, width: 2),
borderRadius: BorderRadius.circular(200),
image: DecorationImage(
image: customAdvanceNetworkImage(
state.userModel.profilePic ?? Constants.dummyProfilePic,
),
fit: BoxFit.cover,
)),
),
SizedBox(
height: 20,
),
ListTile(
onTap: () {
Navigator.push(context,
ProfilePage.getRoute(profileId: state.userModel.userId));
},
title: Row(
children: <Widget>[
UrlText(
text: state.userModel.displayName ?? "",
style: TextStyles.onPrimaryTitleText
.copyWith(color: Colors.black, fontSize: 20),
),
SizedBox(
width: 3,
),
state.userModel.isVerified ?? false
? customIcon(context,
icon: AppIcon.blueTick,
istwitterIcon: true,
iconColor: AppColor.primary,
size: 18,
paddingIcon: 3)
: SizedBox(
width: 0,
),
],
),
subtitle: customText(
state.userModel.userName,
style: TextStyles.onPrimarySubTitleText
.copyWith(color: Colors.black54, fontSize: 15),
),
trailing: customIcon(context,
icon: AppIcon.arrowDown,
iconColor: AppColor.primary,
paddingIcon: 20),
),
Container(
alignment: Alignment.center,
child: Row(
children: <Widget>[
SizedBox(
width: 17,
),
_tappbleText(context, '${state.userModel.getFollower}',
' Connections', 'FollowerListPage'),
SizedBox(width: 10),
_tappbleText(context, '${state.userModel.getFollowing}',
' Mentors', 'FollowingListPage'),
],
),
),
],
),
);
}
}
Widget _tappbleText(
BuildContext context, String count, String text, String navigateTo) {
return InkWell(
onTap: () {
var authstate = context.read<AuthState>();
List<String> usersList;
authstate.getProfileUser();
Navigator.pop(context);
switch (navigateTo) {
case "FollowerListPage":
usersList = authstate.userModel.followersList;
break;
case "FollowingListPage":
usersList = authstate.userModel.followingList;
break;
default:
}
Navigator.push(
context,
FollowerListPage.getRoute(
profile: authstate.userModel, userList: usersList));
},
child: Row(
children: <Widget>[
customText(
'$count ',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17),
),
customText(
'$text',
style: TextStyle(color: AppColor.darkGrey, fontSize: 17),
),
],
),
);
}
ListTile _menuListRowButton(String title,
{Function onPressed, IconData icon, bool isEnable = false}) {
return ListTile(
onTap: () {
if (onPressed != null) {
onPressed();
}
},
leading: icon == null
? null
: Padding(
padding: EdgeInsets.only(top: 5),
child: customIcon(
context,
icon: icon,
size: 25,
iconColor: isEnable ? AppColor.darkGrey : AppColor.lightGrey,
),
),
title: customText(
title,
style: TextStyle(
fontSize: 20,
color: isEnable ? AppColor.secondary : AppColor.lightGrey,
),
),
);
}
Positioned _footer() {
return Positioned(
bottom: 0,
right: 0,
left: 0,
child: Column(
children: <Widget>[
Divider(height: 0),
Row(
children: <Widget>[
TextButton(
onPressed: () {
Navigator.push(
context,
ScanScreen.getRoute(
context.read<AuthState>().profileUserModel));
},
child: Image.asset(
"assets/images/qr.png",
height: 25,
),
),
],
),
],
),
);
}
void _logOut() {
final state = Provider.of<AuthState>(context, listen: false);
Navigator.pop(context);
state.logoutCallback();
}
// ignore: unused_element
void _navigateTo(String path) {
Navigator.pop(context);
Navigator.of(context).pushNamed('/$path');
}
#override
Widget build(BuildContext context) {
return Center(
child: SafeArea(
child: Stack(
children: <Widget>[
Padding(
padding: EdgeInsets.only(bottom: 45),
child: ListView(
physics: BouncingScrollPhysics(),
children: <Widget>[
Container(
child: _menuHeader(),
),
Divider(),
_menuListRowButton('Profile',
icon: AppIcon.profiles, isEnable: true, onPressed: () {
var state = context.read<AuthState>();
Navigator.push(
context, ProfilePage.getRoute(profileId: state.userId));
}),
_menuListRowButton('Help Center',
icon: AppIcon.helped, isEnable: true, onPressed: () {
var state = context.read<AuthState>();
Navigator.push(
context, ProfilePage.getRoute(profileId: state.userId));
}),
_menuListRowButton('Terms of Service',
icon: AppIcon.agreement, isEnable: true, onPressed: () {
var state = context.read<AuthState>();
Navigator.push(
context, ProfilePage.getRoute(profileId: state.userId));
}),
_menuListRowButton('Privacy Policy',
icon: AppIcon.privacy, isEnable: true, onPressed: () {
var state = context.read<AuthState>();
Navigator.push(
context, ProfilePage.getRoute(profileId: state.userId));
}),
_menuListRowButton('Cookie Use',
icon: AppIcon.cookies, isEnable: true, onPressed: () {
var state = context.read<AuthState>();
Navigator.push(
context, ProfilePage.getRoute(profileId: state.userId));
}),
Divider(),
_menuListRowButton('Logout',
icon: AppIcon.logout, onPressed: _logOut, isEnable: true),
],
),
),
_footer()
],
),
),
);
}
}
I want them to open to different urls on the web. If there is anything I should add such as dependencies or import any packages, please let me know.
You can navigate to a webpage with the Url Launcher package.
Future<void> launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Why am I having memory issues with flutter ChangeNotifierProvider?

I am making a shopping cart app in flutter with Change Notifier Provider. It is working fast and well at first. But it takes the more memory, the more I use it. I am adding and removing clearing items from list. Nothing complicated. Cannot know why it is working like this. It is slowing down gradually. This is main.dart:
class Main extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => Cart(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: swatchColor,
primaryColor: primaryColor,
accentColor: tertiaryColor,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.black,
selectionColor: primaryColor,
selectionHandleColor: primaryColor,
),
),
initialRoute: '/login',
routes: {
'/home': (context) => Home(),
'/login': (context) => Login(),
'/tableReview': (context) => TableReview(),
'/createOrder': (context) => CreateOrder(),
'/orderReview': (context) => OrderReview(),
},
),
);
}
}
This is main cart_model.dart
import 'package:counter/data/models/cart_item.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
class Cart extends ChangeNotifier {
List<Item> cart = [];
addItemToCart({#required item}) {
Item newItem = Item(
id: item.id,
price: item.price is int ? item.price : int.parse(item.price),
title: item.title,
);
int i = cart.indexWhere((previousItem) => previousItem.id == newItem.id);
if (i > -1) {
cart[i].count++;
} else {
cart.add(newItem);
}
notifyListeners();
}
removeItemFromCart({#required item}) {
int index = cart.indexWhere((element) => element.id == item.id);
if (index > -1) {
if (cart[index].count > 1) {
cart[index].count--;
} else {
cart.removeWhere((element) => element.id == item.id);
}
}
notifyListeners();
}
clearCart() {
cart.clear();
notifyListeners();
}
int get totalPrice =>
cart.fold(0, (total, current) => total + (current.price * current.count));
}
This is menuitem.dart
class MenuItem extends StatelessWidget {
final dynamic foodItem;
MenuItem({#required this.foodItem});
void _showSecondPage(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) => Scaffold(
backgroundColor: Colors.black45,
body: Center(
child: Hero(
tag: foodItem.imgPath,
child: Image(image: NetworkImage(base_url + foodItem.imgPath)),
),
),
),
),
);
}
#override
Widget build(BuildContext context) {
int itemIndex = Provider.of<Cart>(context, listen: false)
.cart
.indexWhere((item) => item.id == foodItem.id);
return Container(
height: 80,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () => _showSecondPage(context),
child: Hero(
tag: foodItem.imgPath,
child: CircleAvatar(
backgroundImage: NetworkImage(base_url + foodItem.imgPath),
),
),
),
SizedBox(
width: 15,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
foodItem.title,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 17,
),
),
Text('${foodItem.price.toString()} сум'),
],
)
],
),
Container(
width: 160,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon:
Icon(Icons.remove, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
Text(
itemIndex > -1
? '${Provider.of<Cart>(context).cart[itemIndex].count}'
: '0',
style: TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(Icons.add, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
],
),
),
],
),
);
}
}
This is consumer part:
import 'package:counter/common/socketio.dart';
import 'package:counter/data/models/cart_model.dart';
import 'package:counter/presentation/widgets/empty_cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class OrderReview extends StatefulWidget {
#override
_OrderReviewState createState() => _OrderReviewState();
}
class _OrderReviewState extends State<OrderReview> {
bool isCommentEnabled = false;
String guestCount;
String comment = '';
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
final myCart = context.watch<Cart>();
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text('Проверка заказа'),
),
body: Builder(
builder: (context) {
if (myCart.cart.length > 0) {
handleOrderCreate() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userId = prefs.getString('userId');
String tableNum = prefs.getString('tableNum');
String status = 'accepted';
print('$userId, $tableNum, $status');
Map orderToCreate = {
'tableNum': tableNum,
'status': 'accepted',
'userId': userId,
'guestCount': guestCount,
'comment': comment,
'foodList': myCart.cart
};
socketIO.emit('createOrder', json.encode(orderToCreate));
Navigator.of(context).pushNamed('/home');
Provider.of<Cart>(context, listen: false).clearCart();
}
return GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(new FocusNode()),
child: LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: IntrinsicHeight(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Form(
key: _formKey,
child: Column(
children: [
Container(
height: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
boxShadow: [
BoxShadow(
color:
Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0,
3), // changes position of shadow
),
]),
child: ListView.separated(
itemBuilder:
(BuildContext context, int i) {
return ListTile(
title: Text(myCart.cart[i].title),
trailing: Container(
width: 160,
child: Row(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.remove,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.removeItemFromCart(
item: myCart
.cart[i]);
},
),
Text(
'${myCart.cart[i].count}',
style:
TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(
Icons.add,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.addItemToCart(
item: myCart
.cart[i]);
},
),
],
),
),
);
},
separatorBuilder:
(BuildContext context, int) {
return Divider(
height: 2,
color: Colors.grey,
);
},
itemCount: myCart.cart.length,
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Количество гостей',
),
onChanged: (newValue) {
setState(() => guestCount = newValue);
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'Пожалуйста, введите количество гостей!';
}
return null;
},
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
onChanged: (newValue) {
setState(() => comment = newValue);
},
enabled: isCommentEnabled,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText:
'Лаваш острый, хот дог без майонеза и т.д.',
// labelText: 'Комментарий',
),
maxLines: 2,
),
),
Row(
children: [
Text('Комментарий'),
Switch(
value: isCommentEnabled,
onChanged: (bool value) {
setState(() =>
this.isCommentEnabled = value);
},
),
],
)
],
),
),
SizedBox(height: 20),
Row(
children: [
Text(
'Общая цена: ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
SizedBox(width: 20),
Text(
'${myCart.totalPrice} сум',
style: TextStyle(fontSize: 18),
),
],
),
Container(
height: 50,
width: 170,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.resolveWith(
(states) =>
Theme.of(context).primaryColor),
),
onPressed: () {
if (_formKey.currentState.validate()) {
handleOrderCreate();
}
},
child: Text(
'Отправить',
style: TextStyle(
color: Colors.white, fontSize: 18),
),
),
),
],
),
),
),
),
);
},
),
);
} else {
print('111');
return EmptyCart();
}
},
),
);
}
}
Is there something wrong with my code?

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

How to access the function inside a future builder from out side Parent widget or another future builder

i have a future builder which populate a list view ,inside there is a function total() which calculate ,pick the price of each item sum it and assign it to the subtotal variable . on the bottom i am showing the total price if i assiggn subtotal variable then it will return 0 for the first time because my function is in future builder ,i mean the function is executed after the value is assign.so i used another future builder for showing the total amount but i cannot access the total function as it is inside the future builder and it cannot be initialzed outside in the class because it has some data that won't be recognized outside.
so the problem is how can i access total function below ,i thought of global key but i don't know how to use it.
import 'package:flutter/material.dart';
import 'package:restaurant_ui_kit/models/user.dart';
import 'package:restaurant_ui_kit/screens/checkout.dart';
import 'package:restaurant_ui_kit/util/database_helper.dart';
class CartScreen extends StatefulWidget {
#override
_CartScreenState createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen>
with AutomaticKeepAliveClientMixin<CartScreen> {
var db = new DatabaseHelper();
int _subTotal = 0;
List _users = [];
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Padding(
padding: EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
child: FutureBuilder<List>(
future: db.getAllUsers(),
initialData: List(),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
final item = snapshot.data[position];
total(){
for (int i = 0; i < snapshot.data.length; i++) {
if (i == 0){
_subTotal =0;
}
_subTotal = _subTotal +
int.parse(
User.fromMap(snapshot.data[position]).price);
}
return _subTotal;
}
total();
// print('toatl is $_subTotal');
// get your item data here ...
return Dismissible(
key: UniqueKey(),
child: new Card(
color: Colors.white,
elevation: 2.0,
child: new ListTile(
leading: new CircleAvatar(
child: Text(
"${User.fromMap(snapshot.data[position]).name.substring(0, 1)}"),
),
title: new Text(
"User: ${User.fromMap(snapshot.data[position]).price}"),
subtitle: new Text(
"Id: ${User.fromMap(snapshot.data[position]).id}"),
onTap: () => debugPrint(
"${User.fromMap(snapshot.data[position]).id}"),
),
),
background: slideLeftBackground(),
confirmDismiss: (direction) async {
if (direction == DismissDirection.endToStart) {
final bool res = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
"Are you sure you want to delete ${User.fromMap(snapshot.data[position]).name}?"),
actions: <Widget>[
FlatButton(
child: Text(
"Cancel",
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text(
"Delete",
style: TextStyle(color: Colors.red),
),
onPressed: () {
// TODO: Delete the item from DB etc..
setState(() {
// total();
// print(position);
print('toatl is $_subTotal');
if (position == 0) {
//print('index 0 dai');
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
_subTotal = 0;
// print('toatl is 0 $_subTotal');
//snapshot.data.removeAt(position);
} else {
snapshot.data
.removeAt(--position);
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
total();
// print('toatl sewa $_subTotal');
}
//print("removed");
// print('mSubTotal $mSubTotal');
});
Navigator.of(context).pop();
},
),
],
);
});
return res;
}
},
);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
),
floatingActionButton: FloatingActionButton(
tooltip: "Checkout",
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return Checkout();
},
),
);
},
child: Icon(
Icons.arrow_forward,
),
heroTag: Object(),
),
bottomSheet: Card(
elevation: 4.0,
child: Container(
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(10,5,5,5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Total",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w400,
),
),
FutureBuilder(
**future: total(),** the problem is here it cannot be accessed
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
return Text(
snapshot.data.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
);
}
return Container();
}
),
Text(
"Delivery charges included",
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w400,
),
),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(5,5,10,5),
width: 150.0,
height: 50.0,
child: FlatButton(
color: Theme.of(context).accentColor,
child: Text(
"Place Order".toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
onPressed: (){},
),
),
],
),
],
),
height: 70,
),
),
);
}
#override
bool get wantKeepAlive => true;
}
Well first off you can take out your total function and just pass in the data argument once it becomes available in the futurebuilder(like total(data){...}).
Now if you need the data that you got from db.getAllUsers(), you could also create a function like getAllUsers, where you would assign the gotten value to a class variable to be used later. Finally, unless the function total is asynchronous, it does not make sense to have a future builder for it. You can probably get away with calling setState once the total value is available.
Try this
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Padding(
padding: EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
child: FutureBuilder<List>(
future: db.getAllUsers(),
initialData: List(),
builder: (context, snapshot) {
total() {
num subTotal = 0;
for (int i = 0; i < snapshot.data.length; i++) {
subTotal += int.parse(User.fromMap(snapshot.data[i]).price);
}
setState(() {
_subTotal=subTotal;
});
}
if (snapshot.hasData) {
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
final item = snapshot.data[position];
total();
// print('toatl is $_subTotal');
// get your item data here ...
return Dismissible(
key: UniqueKey(),
child: new Card(
color: Colors.white,
elevation: 2.0,
child: new ListTile(
leading: new CircleAvatar(
child: Text(
"${User.fromMap(snapshot.data[position]).name.substring(0, 1)}"),
),
title: new Text(
"User: ${User.fromMap(snapshot.data[position]).price}"),
subtitle: new Text(
"Id: ${User.fromMap(snapshot.data[position]).id}"),
onTap: () => debugPrint(
"${User.fromMap(snapshot.data[position]).id}"),
),
),
background: slideLeftBackground(),
confirmDismiss: (direction) async {
if (direction == DismissDirection.endToStart) {
final bool res = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
"Are you sure you want to delete ${User.fromMap(snapshot.data[position]).name}?"),
actions: <Widget>[
FlatButton(
child: Text(
"Cancel",
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text(
"Delete",
style: TextStyle(color: Colors.red),
),
onPressed: () {
// TODO: Delete the item from DB etc..
setState(() {
// total();
// print(position);
print('toatl is $_subTotal');
if (position == 0) {
//print('index 0 dai');
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
_subTotal = 0;
// print('toatl is 0 $_subTotal');
//snapshot.data.removeAt(position);
} else {
snapshot.data.removeAt(--position);
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
total();
// print('toatl sewa $_subTotal');
}
//print("removed");
// print('mSubTotal $mSubTotal');
});
Navigator.of(context).pop();
},
),
],
);
});
return res;
}
return null;
},
);
},
);
}
return Center(child: CircularProgressIndicator());
},
),
),
floatingActionButton: FloatingActionButton(
tooltip: "Checkout",
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return Checkout();
},
),
);
},
child: Icon(
Icons.arrow_forward,
),
heroTag: Object(),
),
bottomSheet: Card(
elevation: 4.0,
child: Container(
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Total",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w400,
),
),
// changes
Text(
_subTotal.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
),
Text(
"Delivery charges included",
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w400,
),
),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(5, 5, 10, 5),
width: 150.0,
height: 50.0,
child: FlatButton(
color: Theme.of(context).accentColor,
child: Text(
"Place Order".toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
onPressed: () {},
),
),
],
),
],
),
height: 70,
),
),
);
}

How To Dynamically add Dropdown buttons or delete dropdown(s) in listview with flutter Web?

i have created a page where a user who will click a title to edit the contents and can add and delete devices that the article is attached to,
but i could not figure it out on how to program the drop down dynamically, to add more drop downs when a user press the add device button,
the additional function they want me to add as well is on the Dropdown list, when they select 'NONE' it should remove that dropdown as well,
i am planning to use mysql,xampp or sqlite for my database if im done with the UI,
import 'package:flutter/material.dart';
import 'package:surveyadminpanel/Contents/tabbar.dart';
import 'package:surveyadminpanel/widgets/button.dart';
import 'package:surveyadminpanel/widgets/simplewidgets.dart';
import 'homepage.dart';
import 'dart:ui';
class Item {
Item(this.name);
String name;
}
class editsurvey extends StatefulWidget {
#override
_editsurveyState createState() => _editsurveyState();
}
class _editsurveyState extends State<editsurvey>{
int surveyquestionnum = 1;
int surveyquestiontotal = 1;
List<Item> selectedUser = [null, null];
List<Item> selecteddata = [null, null];
List<Item> users;
int linkdevices = 1;
String dropdownvalue= "SELECT FROM DROPDOWN";
List data = [
'Sample Data 1',
'Sample Data 2',
'Sample Data 3',
'Sample Data 4',
'Sample Data 5',
'Sample Data 6',
];
#override
void initState() {
super.initState();
users = <Item>[
Item('Sample device 1'),
Item('Sample device 2'),
Item('Sample device 3'),
Item('Sample device 4'),
];
}
#override
Widget _dropdownbutton (List<Item> userlist, int index){
return Container(
padding: EdgeInsets.all(1),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(15.0) //
),
),
child: DropdownButton<Item>(
underline: SizedBox(),
isExpanded: true,
icon: Icon(Icons.arrow_drop_down),
hint: Text(" $dropdownvalue"),
value: selectedUser[index],
onChanged: (Item Value) {
setState(() {
selectedUser[index] = Value;
});
},
items: userlist.map((Item user) {
return DropdownMenuItem<Item>(
value: user,
child: Row(
children: <Widget>[
SizedBox(width: 10,),
Text(
user.name,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
);
}
Widget _text(texthere,bold,size,color){
return Text(texthere,style: TextStyle(fontWeight: bold,fontSize: size,color: color),overflow: TextOverflow.ellipsis,maxLines: 1);
}
Widget _logo(){
return InkWell(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => admincontent()),
);
},
child: Container(width: 500,height: 200,child: Image.asset("images/v2.jpg")));
}
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: Padding(padding: EdgeInsets.only(left: 30),
child: RichText(
text: TextSpan(
text: 'Good Morning Welcome to Sample:',
style: TextStyle(
color: Colors.blueAccent, fontSize: 18),
children: <TextSpan>[
TextSpan(text: usernametitle,
style: TextStyle(
color: Colors.black, fontSize: 18),
)
]
),
)
),
elevation: 1,
automaticallyImplyLeading: false,
backgroundColor: Colors.white,
leading: _logo(),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
color: Colors.blueAccent,
tooltip: 'Show Notification',
onPressed: () {
},
),
IconButton(
color: Colors.lightGreen,
icon: const Icon(Icons.account_circle),
tooltip: 'Check your Profile',
onPressed: () {
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_text("EDIT SURVEY", FontWeight.bold, 20,Colors.blue),
roundedRectButton("BACK", signInGradients),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
width: screenWidth/1.6,
height: screenHeight/1.6,
decoration: BoxDecoration(
color: Colors.orange[200],
borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_text("SURVEY TITLE", FontWeight.bold, 17,Colors.white),
_text(data[0], FontWeight.bold, 19, Colors.black),
_text("DATE CREATED", FontWeight.bold, 17,Colors.white),
_text(data[1], null, 19, Colors.black),
_text("CURRENT STATUS", FontWeight.bold, 17,Colors.white),
_text(data[2], null, 19, Colors.black),
_text("LANGUAGE VERSION", FontWeight.bold, 17,Colors.white),
_text(data[3], null, 19, Colors.black),
_text("NUMBERS OF ASSESSORS", FontWeight.bold, 17,Colors.white),
_text(data[4], null, 19, Colors.black),
_text("TOTAL RENDERED SURVEYS", FontWeight.bold, 17,Colors.white),
_text(data[5], null, 19, Colors.black),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: (){
},
child: Container(width: 100,height: 50,child: Text("EDIT SURVEY")),
),
_text("LINKED DEVICES : $linkdevices", FontWeight.bold, 17,Colors.white),
],
)
],
),
)
),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 1.0,
style: BorderStyle.solid
)
),
width: screenWidth/1.6,
height: screenHeight/1.6,
child: Column(
children: <Widget>[
_text("DEVICES PINNED", FontWeight.bold, 20,Colors.blue),
ListView.separated(
shrinkWrap: true,
itemCount: linkdevices,
itemBuilder: (context, index){
return Padding(
padding: const EdgeInsets.all(8.0),
child: _dropdownbutton(users, index),
);
},
separatorBuilder: (context, index) => Container(height: 10),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
child: roundedRectButton("ADD DEVICE", signInGradients),
onTap: (){
},
),
InkWell(
child: roundedRectButton("CLEAR ALL DEVICE", signInGradients),
onTap: (){
},
),
],
),
],
),
),
],
)
],
),
),
),
);
}
}
The Plan
The Result
im still trying to figure this out, but if someone can give me a lift,, im gonna be very thankful to who can help me out here ,,
You can copy paste run full code below
You can increase linkdevices and selectedUser
code snippet
List<Item> selectedUser = [null];
...
InkWell(
child: Text("ADD DEVICE"),
onTap: () {
selectedUser.add(null);
linkdevices ++;
setState(() {
});
working demo
full code
import 'package:flutter/material.dart';
class Item {
Item(this.name);
String name;
}
class editsurvey extends StatefulWidget {
#override
_editsurveyState createState() => _editsurveyState();
}
class _editsurveyState extends State<editsurvey> {
int surveyquestionnum = 1;
int surveyquestiontotal = 1;
List<Item> selectedUser = [null];
List<Item> selecteddata = [null, null];
List<Item> users;
int linkdevices = 1;
String dropdownvalue = "SELECT FROM DROPDOWN";
List data = [
'Sample Data 1',
'Sample Data 2',
'Sample Data 3',
'Sample Data 4',
'Sample Data 5',
'Sample Data 6',
];
#override
void initState() {
super.initState();
users = <Item>[
Item('Sample device 1'),
Item('Sample device 2'),
Item('Sample device 3'),
Item('Sample device 4'),
];
}
#override
Widget _dropdownbutton(List<Item> userlist, int index) {
return Container(
padding: EdgeInsets.all(1),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(Radius.circular(15.0) //
),
),
child: DropdownButton<Item>(
underline: SizedBox(),
isExpanded: true,
icon: Icon(Icons.arrow_drop_down),
hint: Text(" $dropdownvalue"),
value: selectedUser[index],
onChanged: (Item Value) {
print(Value.toString());
print(index);
setState(() {
selectedUser[index] = Value;
});
},
items: userlist.map((Item user) {
return DropdownMenuItem<Item>(
value: user,
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
user.name,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
);
}
Widget _text(texthere, bold, size, color) {
return Text(texthere,
style: TextStyle(fontWeight: bold, fontSize: size, color: color),
overflow: TextOverflow.ellipsis,
maxLines: 1);
}
Widget _logo() {
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => admincontent()),
);
},
child: Container(
width: 500, height: 200, child: Image.asset("images/v2.jpg")));
}
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: Padding(
padding: EdgeInsets.only(left: 30),
child: RichText(
text: TextSpan(
text: 'Good Morning Welcome to Sample:',
style: TextStyle(color: Colors.blueAccent, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: "usernametitle",
style: TextStyle(color: Colors.black, fontSize: 18),
)
]),
)),
elevation: 1,
automaticallyImplyLeading: false,
backgroundColor: Colors.white,
leading: _logo(),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
color: Colors.blueAccent,
tooltip: 'Show Notification',
onPressed: () {},
),
IconButton(
color: Colors.lightGreen,
icon: const Icon(Icons.account_circle),
tooltip: 'Check your Profile',
onPressed: () {},
),
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_text("EDIT SURVEY", FontWeight.bold, 20.0, Colors.blue),
//roundedRectButton("BACK", signInGradients),
Text("BACK"),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
width: screenWidth / 1.6,
height: screenHeight / 1.6,
decoration: BoxDecoration(
color: Colors.orange[200],
borderRadius:
new BorderRadius.all(new Radius.circular(20.0)),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_text("SURVEY TITLE", FontWeight.bold, 17.0,
Colors.white),
_text(data[0], FontWeight.bold, 19.0, Colors.black),
_text("DATE CREATED", FontWeight.bold, 17.0,
Colors.white),
_text(data[1], null, 19.0, Colors.black),
_text("CURRENT STATUS", FontWeight.bold, 17.0,
Colors.white),
_text(data[2], null, 19.0, Colors.black),
_text("LANGUAGE VERSION", FontWeight.bold, 17.0,
Colors.white),
_text(data[3], null, 19.0, Colors.black),
_text("NUMBERS OF ASSESSORS", FontWeight.bold, 17.0,
Colors.white),
_text(data[4], null, 19.0, Colors.black),
_text("TOTAL RENDERED SURVEYS", FontWeight.bold,
17.0, Colors.white),
_text(data[5], null, 19.0, Colors.black),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: () {},
child: Container(
width: 100,
height: 50,
child: Text("EDIT SURVEY")),
),
_text("LINKED DEVICES : $linkdevices",
FontWeight.bold, 17.0, Colors.white),
],
)
],
),
)),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 1.0,
style: BorderStyle.solid)),
width: screenWidth / 1.6,
height: screenHeight / 1.6,
child: Column(
children: <Widget>[
_text("DEVICES PINNED", FontWeight.bold, 20.0,
Colors.blue),
ListView.separated(
shrinkWrap: true,
itemCount: linkdevices,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: _dropdownbutton(users, index),
);
},
separatorBuilder: (context, index) => Container(height: 10),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
child: Text("ADD DEVICE"),
onTap: () {
selectedUser.add(null);
linkdevices ++;
setState(() {
});
/*listWidget.add( ListView.separated(
shrinkWrap: true,
itemCount: linkdevices,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: _dropdownbutton(users, index),
);
},
separatorBuilder: (context, index) => Container(height: 10),
));
setState(() {
});*/
},
),
InkWell(
child: Text("CLEAR ALL DEVICE"),
onTap: () {},
),
],
),
],
),
),
],
)
],
),
),
),
);
}
}
class admincontent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container();
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: editsurvey(),
);
}
}