I'm working on an application to process a list of items using a bluetooth barcode scanner. When the page loads the user will have to scan the location barcode and if it is correct the focus will shift to the item barcode but while the item Widget shows up I get ViewPostIme key 1/0 in my console log and nothing happens.
Furthurmore while the shifting from Location to Item Widget focus works, it looks very glitchy like the soft keyboard animation is shown and hidden multiple times quickly.
inventPickTrans.dart
class InventPickTrans {
String itemId = "";
String itemName = "";
String itemPackBarCode = "";
String itemUnitBarCode = "";
String wmsLocationId = "";
pick_picking_sceen.dart
import 'package:provider/provider.dart';
import 'package:app/picking_provider.dart';
import 'package:flutter/material.dart';
import 'package:app/NoKeyboardEditableText.dart';
import 'package:app/inventPickTrans.dart';
List<InventPickTrans>? lstInventPickTrans;
class PickPickingScreen extends StatefulWidget {
static const String routeName = '/pick_picking_screen';
PickPickingScreen();
#override
_PickPickingScreenState createState() => _PickPickingScreenState();
}
class AlwaysDisabledFocusNode extends FocusNode {
#override
bool get hasFocus => false;
}
class _PickPickingScreenState extends State<PickPickingScreen>
with SingleTickerProviderStateMixin{
TextEditingController locationInputController = TextEditingController();
TextEditingController itemInputController = TextEditingController();
FocusNode focusNodeLocation = NoKeyboardEditableTextFocusNode();
FocusNode focusNodeItem = NoKeyboardEditableTextFocusNode();
#override
void initState() {
super.initState();
}
#override
void dispose() {
context.read<PickingProvider>().setItemInitialised(false);
focusNodeLocation.dispose();
focusNodeItem.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final inventPickTrans = context.read<PickingProvider>().workingInventPickTrans;
int itemIndex = context.read<PickingProvider>().itemIndex;
initPicklistSetup();
return Scaffold(
backgroundColor: Color.fromARGB(255, 29,161,125),
body: Container(
child: Column( //Outer
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
customRow(context, itemIndex, inventPickTrans![itemIndex]),
],
),
),
);
}
customRow(BuildContext context, int itemIndex, InventPickTrans inventPickTrans) {
if (context.read<PickingProvider>().isPicked[itemIndex]){
//PICKED
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
decoration: BoxDecoration(
color: Colors.yellow,
border: Border.all(
color: Color.fromARGB( 255, 29, 161, 125)
),
borderRadius: BorderRadius.all(Radius.circular(5)),
),
width: MediaQuery.of(context).size.width,
child: Center(
child: Text('PICKED',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 40,
color: Color.fromARGB(255, 29, 161, 125),
fontWeight: FontWeight.w900,
),
),
),
)
)
)
]
);
}else if (!context.read<PickingProvider>().isLocationConfirmed[itemIndex]) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.white,
),
borderRadius: BorderRadius.all(Radius.circular(5)),
),
width: MediaQuery.of(context).size.width,
child: Center(
child: Text('Scan Location: ' +
inventPickTrans.wmsLocationId.toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 40,
color: Color.fromARGB(
255, 29, 161, 125),
fontWeight: FontWeight.w900,
),
),
),
),
),
),
SizedBox(
width: 0,
height: 0,
child: NoKeyboardEditableText(
autofocus: true,
controller: locationInputController,
focusNode: focusNodeLocation,
textInputAction: TextInputAction.next,
style: TextStyle(),
cursorColor: Colors.white,
onSubmitted: (value) {
setState(() {
if (inventPickTrans.wmsLocationId == value) {
context.read<PickingProvider>().setLocationConfirmed(
true, itemIndex);
print('location scan success');
FocusScope.of(context).requestFocus(focusNodeItem);
} else {
context.read<PickingProvider>().setLocationConfirmed(
false, itemIndex);
print('location scan failure');
locationInputController.clear();
FocusScope.of(context).requestFocus(focusNodeLocation);
}
});
},
),
),
],
);
}else if(context.read<PickingProvider>().isLocationConfirmed[itemIndex] && !context.read<PickingProvider>().isItemConfirmed[itemIndex]){
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.white,
),
borderRadius: BorderRadius.all(Radius.circular(5)),
),
width: MediaQuery.of(context).size.width,
child: Center(
child: Text('Scan Item: ' + inventPickTrans.itemId.toString() + ' ' + inventPickTrans.itemName.toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 40,
color: Color.fromARGB(255, 29, 161, 125),
fontWeight: FontWeight.w900,
),
),
),
),
),
),
SizedBox(
width: 0,
height: 0,
child: NoKeyboardEditableText(
autofocus: true,
controller: itemInputController,
focusNode: focusNodeItem,
textInputAction: TextInputAction.next,
style: TextStyle(),
cursorColor: Colors.white,
onSubmitted: (value) {
setState(() {
if (inventPickTrans.itemUnitBarCode == value || inventPickTrans.itemPackBarCode == value) {
context.read<PickingProvider>().setItemConfirmed(
true, itemIndex);
FocusScope.of(context).unfocus();
print('item scan success');
} else {
context.read<PickingProvider>().setItemConfirmed(
false, itemIndex);
itemInputController.clear();
FocusScope.of(context).requestFocus(focusNodeItem);
print('item scan failure');
}
});
},
),
),
],
);
}else if(context.read<PickingProvider>().isLocationConfirmed[itemIndex] && context.read<PickingProvider>().isItemConfirmed[itemIndex]){
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Icon(
Icons.check_circle_rounded,
color: Colors.yellow,
size: 40.0,
)
),
)
)
)
]
);
}else{
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Icon(
Icons.refresh_rounded,
color: Colors.white,
size: 40.0,
)
),
)
)
)
]
);
}
}
}
class NoKeyboardEditableTextFocusNode extends FocusNode {
#override
bool consumeKeyboardToken() {
return false;
}
}
NoKeyboardEditableText.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NoKeyboardEditableText extends EditableText {
NoKeyboardEditableText({
required TextEditingController controller,
required TextStyle style,
required Color cursorColor,
required onSubmitted(String value),
required FocusNode focusNode,
required TextInputAction textInputAction,
//required onChanged(String value),
bool autofocus = true,
Color? selectionColor
}):super(
controller: controller,
focusNode: focusNode,
style: style,
cursorColor: cursorColor,
autofocus: autofocus,
selectionColor: selectionColor,
backgroundCursorColor: Colors.black,
//onChanged: onChanged,
onSubmitted: onSubmitted,
textInputAction: textInputAction,
);
#override
EditableTextState createState() {
return NoKeyboardEditableTextState();
}
}
class NoKeyboardEditableTextState extends EditableTextState {
#override
void requestKeyboard() {
super.requestKeyboard();
//hide keyboard
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
}
class NoKeyboardEditableTextFocusNode extends FocusNode {
#override
bool consumeKeyboardToken() {
// prevents keyboard from showing on first focus
return false;
}
}
picking_provider.dart
import 'package:flutter/material.dart';
import 'package:app/inventPickTrans.dart';
class PickingProvider with ChangeNotifier{
bool _itemInitialised = false;
bool _picklistInitialised = false;
List<bool> _isLocationConfirmed = [false];
List<bool> _isItemConfirmed = [false];
List<bool> _isPicked = [false];
List<InventPickTrans>? _workingInventPickTrans = [];
int _itemIndex = 0;
List<bool> get isLocationConfirmed => _isLocationConfirmed;
void setLocationConfirmed(bool _clc, int _ii){
_isLocationConfirmed[_ii] = _clc;
notifyListeners();
}
void initLocationConfirmed(List<bool> _c){
_isLocationConfirmed.clear();
_isLocationConfirmed.insertAll(_isLocationConfirmed.length, _c);
notifyListeners();
}
List<bool> get isItemConfirmed => _isItemConfirmed;
void setItemConfirmed(bool _cip, int _ii){
_isItemConfirmed[_ii] = _cip;
notifyListeners();
}
void initItemConfirmed(List<bool> _c){
_isItemConfirmed.clear();
_isItemConfirmed.insertAll(_isItemConfirmed.length, _c);
notifyListeners();
}
List<InventPickTrans>? get workingInventPickTrans => _workingInventPickTrans;
void setWorkingInventPickTrans(List<InventPickTrans>? _wrol){
_workingInventPickTrans = [];
for(final e in _wrol!){
InventPickTrans line = InventPickTrans.fromJson(e.toJson());
_workingInventPickTrans!.add(line);
}
notifyListeners();
}
bool get itemInitialised => _itemInitialised;
void setItemInitialised(bool _ii){
_itemInitialised = _ii;
notifyListeners();
}
bool get picklistInitialised => _picklistInitialised;
void setPicklistInitialised(bool _pi){
_picklistInitialised = _pi;
notifyListeners();
}
int get itemIndex => _itemIndex;
void setItemIndex(int _ii){
_itemIndex = _ii;
notifyListeners();
}
List<bool> get isPicked => _isPicked;
void initIsPicked(List<bool> _s){
_isPicked.clear();
_isPicked.insertAll(isPicked.length, _s);
notifyListeners();
}
bool getIsItemPicked( int _ii){
return _isPicked[_ii];
}
void initPicklistSetup( List<InventPickTrans> InventPickTrans){
if (!picklistInitialised){
setWorkingInventPickTrans(InventPickTrans);
if (isPicked.length < workingInventPickTrans!.length) {
List<bool> fillSelected = (List.filled(workingInventPickTrans!.length, false));
initIsPicked(fillSelected);
}
if (isItemConfirmed.length < workingInventPickTrans!.length) {
List<bool> fillEditable = List.filled(workingInventPickTrans!.length - isItemConfirmed.length, false);
initItemConfirmed(fillEditable);
}
if (isLocationConfirmed.length < workingInventPickTrans!.length) {
List<bool> fillEditable = List.filled(workingInventPickTrans!.length - isLocationConfirmed.length, false);
initLocationConfirmed(fillEditable);
}
setPicklistInitialised(true);
}
}
}
Related
This is a part of a project regarding feedback forms.
I already manage to create the validation form properly thanks to the answers here in StackOverflow developers.
But the problem is creating this regular expression which seems to not work on the validation form. I found in flutter docs the Iterable but I do not know how can I implement it on the dart page.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class SimpleDialog extends StatelessWidget {
// ignore: prefer_typing_uninitialized_variables
final title;
const SimpleDialog(this.title, {super.key});
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Alert'),
content: Text(title),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'))
],
);
}
}
class FeedbackPage extends StatefulWidget {
const FeedbackPage({super.key});
#override
State<FeedbackPage> createState() => _FeedbackPageState();
}
class _FeedbackPageState extends State<FeedbackPage> {
final nameOfuser = TextEditingController();
final emailOfuser = TextEditingController();
final messageOfuser = TextEditingController();
final _formKey = GlobalKey<FormState>();
List<bool> isTypeSelected = [false, false, false, true, true];
#override
Widget build(BuildContext context) {
return Scaffold(
// AppBar para sa taas ng design
appBar: AppBar(
centerTitle: true,
title: const Text(
"PicLeaf",
style: TextStyle(
color: Color.fromRGBO(102, 204, 102, 1.0),
fontWeight: FontWeight.bold),
),
backgroundColor: Colors.white,
shadowColor: const Color.fromARGB(255, 95, 94, 94),
),
//body of the application
backgroundColor: const Color(0xffeeeeee),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const SizedBox(
height: 20,
),
const Text(
"Feedback",
style: TextStyle(
fontSize: 30.0,
fontFamily: 'RobotoBold',
fontWeight: FontWeight.bold,
color: Color.fromRGBO(102, 204, 102, 1.0)),
),
const Text(
"Give us your feedback!",
style: TextStyle(
fontSize: 18.0,
fontFamily: 'RobotoMedium',
),
),
const SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
const SizedBox(height: 16.0),
TextFormField(
controller: nameOfuser,
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Name",
border: OutlineInputBorder(),
),
validator: (nameOfuser) {
if (nameOfuser == null || nameOfuser.isEmpty) {
return 'Please enter your Name';
}
return null;
},
),
const SizedBox(height: 8.0),
TextFormField(
controller: emailOfuser,
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Email",
border: OutlineInputBorder(),
),
validator: (emailOfuser) {
if (emailOfuser == null || emailOfuser.isEmpty) {
String emailOfuser1 = emailOfuser.toString();
String pattern = r'\w+#\w+\.\w+';
if (RegExp(pattern).hasMatch(emailOfuser1)) {
return 'Please enter your Email Properly';
} else {
return 'Please enter your Email';
}
}
return null;
},
),
const SizedBox(height: 8.0),
TextFormField(
controller: messageOfuser,
maxLines: 6,
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Message",
border: OutlineInputBorder(),
),
validator: (messageOfuser) {
if (messageOfuser == null || messageOfuser.isEmpty) {
return 'Please enter your Message';
}
return null;
},
),
const SizedBox(height: 8.0),
MaterialButton(
height: 50.0,
minWidth: double.infinity,
color: const Color.fromRGBO(102, 204, 102, 1.0),
onPressed: () {
if (_formKey.currentState!.validate()) {
showDialog(
context: context,
builder: (BuildContext context) {
return const SimpleDialog(
'Feedback Submitted');
});
Map<String, dynamic> data = {
"Name": nameOfuser.text,
"Email": emailOfuser.text,
"Message": messageOfuser.text,
"Time": FieldValue.serverTimestamp(),
};
setState(() {
nameOfuser.clear();
emailOfuser.clear();
messageOfuser.clear();
});
FirebaseFirestore.instance
.collection("FeedbackMessages")
.add(data);
}
},
child: const Text(
"SUBMIT",
style: TextStyle(
fontFamily: 'RobotoBold',
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const SizedBox(
height: 10,
),
Container(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 10),
child: const Text(
'Contact Us!',
style: TextStyle(
fontSize: 30,
fontFamily: 'RobotoBold',
color: Color.fromRGBO(102, 204, 102, 1.0)),
textAlign: TextAlign.center,
),
),
Column(
children: <Widget>[
Container(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
margin: const EdgeInsets.symmetric(horizontal: 0),
child: TextButton.icon(
// <-- TextButton
onPressed: () {},
icon: const Icon(
Icons.facebook,
color: Colors.black,
size: 35.0,
),
label: const Text(
'facebook.com/picleaf',
style: TextStyle(fontFamily: 'RobotoMedium'),
),
style: TextButton.styleFrom(
foregroundColor: Colors.black,
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
margin: const EdgeInsets.symmetric(horizontal: 0),
child: TextButton.icon(
// <-- TextButton
onPressed: () {},
icon: const Icon(
Icons.email,
color: Colors.black,
size: 35.0,
),
label: const Text(
'picleaf#gmail.com',
style: TextStyle(fontFamily: 'RobotoMedium'),
),
style: TextButton.styleFrom(
foregroundColor: Colors.black,
),
)),
],
)
],
),
),
),
],
),
));
}
}
You can use this validator:
validator: (emailOfuser) {
if (emailOfuser == null || emailOfuser.isEmpty) {
return 'Please enter your Email';
} else if (emailOfuser.isNotEmpty) {
String emailOfuser1 = emailOfuser.toString();
String pattern = r'\w+#\w+\.\w+';
if (RegExp(pattern).hasMatch(emailOfuser1) == false) {
return 'Please enter your Email Properly';
}
}
return null;
},
try to implement like this:
import 'package:flutter/material.dart';
class EmailValidationForm extends StatefulWidget {
const EmailValidationForm({Key? key}) : super(key: key);
#override
State<EmailValidationForm> createState() => _EmailValidationFormState();
}
class _EmailValidationFormState extends State<EmailValidationForm> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Email Validation'),
),
body: Form(
key: formKey,
child: Column(
children: [
TextFormField(
autofocus: false,
maxLength: 300,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
validator: (email) {
if (email!.isEmpty) {
return 'required field';
} else if (email.trim().contains(' ')) {
return 'contain space';
} else if (!emailValid(email)) {
return 'invalid email';
}
return null;
},
onSaved: (email) {
return debugPrint(email);
},
),
ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) {
formKey.currentState!.save();
}
},
child: const Text('Validate')),
],
),
),
);
}
}
bool emailValid(String email) {
final RegExp regex = RegExp(
r"^(([^<>()[\]\\.,;:\s#\']+(\.[^<>()[\]\\.,;:\s#\']+)*)|(\'.+\'))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$");
return regex.hasMatch(email.trim());
}
i have a list which contains list of images, i want to show these in my grid view builder if list if not empty other wise i just want to show static + symbol in my grid view builder.
it is my list
var otherPersonOfferList = <Inventory>[].obs;
and this is my grid view builder which i have extracted as a widget and using it in my screen
import 'package:bartermade/models/Get_Inventory.dart';
import 'package:bartermade/models/inventory.dart';
import 'package:bartermade/widgets/inventoryTile.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/inventoryController.dart';
class OfferGrid extends StatefulWidget {
OfferGrid(
{Key? key,
required this.list,
required this.modelSheetHeading,
required this.gestureState})
: super(key: key);
String modelSheetHeading;
List<Inventory> list;
bool gestureState;
#override
State<OfferGrid> createState() => _OfferGridState();
}
class _OfferGridState extends State<OfferGrid> {
InventoryController inventoryController = Get.find();
bool isDeleting = false;
#override
Widget build(BuildContext context) {
if (widget.gestureState == true
? (inventoryController.otherPersonOfferList == [] ||
inventoryController.otherPersonOfferList.length == 0 ||
inventoryController.otherPersonOfferList.isEmpty)
: (inventoryController.myOfferList == [] ||
inventoryController.myOfferList.length == 0 ||
inventoryController.myOfferList.isEmpty)) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
context: context,
builder: (context) {
return InventoryTile(
modelSheetHeading: widget.modelSheetHeading,
list: widget.gestureState == true
? inventoryController.traderInventoryList
: inventoryController.myInventoryList1,
inventoryController: inventoryController,
gestureState: widget.gestureState);
});
},
child: Container(
height: 90,
width: 90,
decoration: BoxDecoration(border: Border.all(color: Colors.black)),
child: Icon(
Icons.add,
size: 35,
),
),
),
);
} else {
return GridView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: widget.list.length + 1,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (context, index) {
if (index == widget.list.length) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
context: context,
builder: (context) {
return InventoryTile(
modelSheetHeading: widget.modelSheetHeading,
list: widget.gestureState == true
? inventoryController.traderInventoryList
: inventoryController.myInventoryList1,
inventoryController: inventoryController,
gestureState: widget.gestureState);
});
},
child: Container(
height: 30,
width: 30,
decoration:
BoxDecoration(border: Border.all(color: Colors.black)),
child: Icon(
Icons.add,
size: 35,
),
),
),
);
} else {
return Stack(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onLongPress: () {
setState(() {
isDeleting = true;
});
},
onTap : (){
setState(() {
isDeleting = false;
});
},
child: CachedNetworkImage(
fit: BoxFit.cover,
height: 100,
width: 200,
imageUrl: // "https://asia-exstatic-vivofs.vivo.com/PSee2l50xoirPK7y/1642733614422/0ae79529ef33f2b3eb7602f89c1472b3.jpg"
"${widget.list[index].url}",
placeholder: (context, url) => Center(
child: CircularProgressIndicator(
color: Colors.grey,
),
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
),
isDeleting == true
? Positioned(
right: 0,
top: 0,
child: CircleAvatar(
backgroundColor: Colors.red,
radius: 10,
child: Icon(
Icons.remove,
size: 14,
),
),
)
: SizedBox()
],
);
}
});
}
}
}
and this is my screen where is just want to check if my list is non empty then fill my grid view with images otherwise just show + sign in grid view
import 'package:bartermade/controllers/inventoryController.dart';
import 'package:bartermade/models/Get_Inventory.dart';
import 'package:bartermade/models/inventory.dart';
import 'package:bartermade/screens/chat/chatScreen.dart';
import 'package:bartermade/utils/app_colors.dart';
import 'package:bartermade/widgets/snackBar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../../../services/inventoryService.dart';
import '../../../../widgets/offerGrid.dart';
class OfferTradeScreen extends StatefulWidget {
String postUserId;
String postUserName;
OfferTradeScreen({
Key? key,
required this.postUserId,
required this.postUserName,
}) : super(key: key);
#override
State<OfferTradeScreen> createState() => _OfferTradeScreenState();
}
class _OfferTradeScreenState extends State<OfferTradeScreen> {
// TradeController tradeController = Get.put(TradeController());
InventoryController inventoryController = Get.put(InventoryController());
// GiftStorageService giftStorageService = GiftStorageService();
// GiftController giftController = Get.put(GiftController());
// ProfileController profileController = Get.put(ProfileController());
// TradeStorageService tradeStorageService = TradeStorageService();
// TradingService tradingService = TradingService();
// PreferenceService preferenceService = PreferenceService();
late List<Inventory> otherPersonList;
late List<Inventory> myList;
#override
void initState() {
super.initState();
inventoryController.getOtherUserInventory(widget.postUserId);
otherPersonList = inventoryController.otherPersonOfferList;
myList = inventoryController.myOfferList;
}
otherPersonlistener() {
inventoryController.otherPersonOfferList.listen((p0) {
if (this.mounted) {
setState(() {
otherPersonList = p0;
});
}
});
}
mylistener() {
inventoryController.myOfferList.listen((p0) {
if (this.mounted) {
setState(() {
myList = p0;
});
}
});
}
int draggableIndex = 0;
#override
Widget build(BuildContext context) {
print("-------building------");
otherPersonlistener();
mylistener();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
leading: GestureDetector(
onTap: () {
inventoryController.myOfferList.clear();
inventoryController.otherPersonOfferList.clear();
Get.back();
},
child: Icon(Icons.arrow_back)),
title: Text(
"Offer",
style: TextStyle(color: Colors.white),
),
actions: [
Padding(
padding: const EdgeInsets.only(right: 15),
child: GestureDetector(
onTap: () {
Get.to(() => ChatScreen(
currentUserId: widget.postUserId,
recieverId: inventoryController.userId.toString()));
},
child: Icon(Icons.message)),
)
],
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
flex: 10,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 20),
child: Text(
"${widget.postUserName} Inventory",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w400),
),
),
OfferGrid(
gestureState: true,
list: otherPersonList,
modelSheetHeading: "${widget.postUserName}",
)
],
),
),
),
Expanded(
flex: 1,
child: Divider(
thickness: 2,
color: Colors.black,
height: 3,
),
),
Expanded(
flex: 10,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"My Inventory",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w400),
),
OfferGrid(
gestureState: false,
list: myList,
modelSheetHeading: "My Inventory",
)
],
),
),
),
Center(child: Obx(() {
return inventoryController.makingOffer.value == true
? CircularProgressIndicator(
color: AppColors.pinkAppBar,
)
: ElevatedButton(
onPressed: () {
if (inventoryController.otherPersonOfferList.isEmpty &&
inventoryController.myOfferList.isEmpty) {
showSnackBar(
"Please add both inventories to make offer",
context);
} else {
inventoryController.postOffer(
widget.postUserId, context);
}
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 50)),
child: Text("Send Offer"));
}))
],
),
),
);
}
#override
void dispose() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
}
User following code :
GridView.builder(
shrinkWrap: true,
itemCount: data.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 17,
mainAxisSpacing: 17,
),
itemBuilder: (
context,
index,
) {
return Obx(
() => InkWell(
onTap: () {
},
child: ClipRRect(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: ColorConfig.colorDarkBlue, width: 2),
image: DecorationImage(
image: AssetImage(ImagePath.unselectedContainer), ///imageURL
fit: BoxFit.fill,
)),
child: Center(
child: Text(data[index].heading,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: ThemeConstants.textThemeFontSize18,
fontWeight: FontWeight.w700,
color: ColorConfig.colorDarkBlue)),
),
height: 150,
),
),
),
);
},
),
I resolved my current issue regarding locking and unlocking buttons. I am basing my levels on the marks the user got. If they got a score of 25 and above, they will proceed to the next level.
Now the problem here is since my quiz is sharing one code with a different JSON file, when the user perfects the score on the first stage, the whole level will unlock which is a no-no. The idea is even they scored perfect, the next stage will be unlocked not the whole level. I tried thinking of ways on how to do it but nothing comes to my mind.
Here is my Quiz Page:
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:baybay_app/Quiz/NextLevel class.dart';
import 'package:baybay_app/Quiz/QuizHome.dart';
import 'package:baybay_app/Quiz/ResultPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class Quizjson extends StatelessWidget {
String roundName;
bool isComplete = false;
Quizjson(this.roundName, mark);
String assettoload;
int question;
// a function
// sets the asset to a particular JSON file
// and opens the JSON
setasset() {
if (roundName == 'Easy Round') {
assettoload ='assets/Sample.json';
} else if (roundName == 'Average Round') {
assettoload = 'assets/Medium.json';
} else if (roundName == 'Hard Round') {
assettoload = 'assets/Hard.json';
}else {
assettoload = 'assets/Intermediate.json';
}
}
#override
Widget build(BuildContext context) {
setasset();
return FutureBuilder(
future: DefaultAssetBundle.of(context).loadString(assettoload, cache: false),
builder: (context, snapshot){
List mydata = json.decode(snapshot.data.toString());
if(mydata == null){
return Scaffold(
body: Center(
child: Text(
"Loading",
),
),
);
}else{
return quizpage(mydata: mydata);
}
}
);
}
}
class quizpage extends StatefulWidget {
String langname;
var mydata;
quizpage({Key key, #required this.mydata}): super(key: key);
#override
_quizpageState createState() => _quizpageState(mydata);
}
class _quizpageState extends State<quizpage> {
var mydata;
_quizpageState(this.mydata);
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 3,
child: Container(
padding: EdgeInsets.all(20.0),
alignment: Alignment.bottomLeft,
child: Text(mydata[0][question.toString()])
),
),
Expanded(
flex: 6,
child: Container(
child: Column(
children: [
Row(
children:[
ChoiceButton("a"),
ChoiceButton("b")
]
),
Row(
children: [
ChoiceButton("c"),
ChoiceButton("d"),
]
)
]
),
),
),
Expanded(
flex: 1,
child: Container(
alignment: Alignment.topCenter,
child: Center(
child: Text(
showtimer,
style: TextStyle(
fontSize: 20.0
),
),
),
),
),
],
)
);
}
Widget ChoiceButton(String k) {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 10.0),
child: MaterialButton(
onPressed: ()=>CheckAnswer(k),
child: Text(
mydata[1][question.toString()][k],
style: TextStyle(
color: Colors.white
)),
color: btncolor[k],
),
);
}
Color colorsToShow = Colors.brown[700];
Color right = Colors.greenAccent[700];
Color wrong = Colors.redAccent[700];
int mark = 0;
int question = 1;
int timer = 30;
String showtimer = "30";
bool canceltimer = false;
bool isComplete = false;
Map<String,Color> btncolor = {
"a" : Colors.brown[700],
"b" : Colors.brown[700],
"c" : Colors.brown[700],
"d" : Colors.brown[700],
};
#override
void initState(){
starttimer();
super.initState();
}
#override
void setState(fn){
if(mounted){
super.setState(fn);
}
}
void starttimer() async {
const onesec = Duration(seconds: 1);
Timer.periodic(onesec, (Timer t){
setState(() {
if(timer < 1){
t.cancel();
NextQuestion();
}
else if(canceltimer==true){
t.cancel();
}
else{
timer = timer - 1;
}
showtimer = timer.toString();
});
});
}
void NextQuestion(){
canceltimer = false;
timer = 30;
setState(() {
if(question< 10){
question++;
}
else{
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => ResultPage(mark: mark),
));}
btncolor["a"] = Colors.brown[700];
btncolor["b"] = Colors.brown[700];
btncolor["c"] = Colors.brown[700];
btncolor["d"] = Colors.brown[700];
isComplete = true;
});
starttimer();
}
void CheckAnswer(String k) {
if(mydata[2][question.toString()] == mydata[1][question.toString()][k]){
mark = mark+5;
colorsToShow = right;
}
else{
colorsToShow = wrong;
}
setState(() {
btncolor[k] = colorsToShow;
});
Timer(Duration(seconds: 2), NextQuestion);
}
}
Here is my Quiz Home:
import 'package:baybay_app/Quiz/QuizTracingSound.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:baybay_app/Quiz/QuizTracingSound.dart';
class QuizHome extends StatefulWidget {
int mark = 0;
QuizHome({ #required this.mark });
#override
_QuizHomeState createState() => _QuizHomeState(mark);
}
class _QuizHomeState extends State<QuizHome> {
createAlertDialouge(BuildContext context){
return showDialog(context: context, builder: (context){
return AlertDialog(
title: Text('Not Complete'),
content: Text('Please score 25 above mark'),
actions: [
Center(
child: RaisedButton(
onPressed: (){Navigator.of(context).pop();},
color: Colors.grey[100],
),
),
],
shape: RoundedRectangleBorder(side: BorderSide(width: 16.0, color: Colors.red.shade100)),
backgroundColor: Colors.lightBlue.shade100,
);
});
}
createAlertDialougeOne(BuildContext context){
return showDialog(context: context, builder: (context){
return AlertDialog(
title: Text('Not Complete'),
content: Text('Please score 35 and above mark'),
actions: [
Center(
child: RaisedButton(
onPressed: (){Navigator.of(context).pop();},
color: Colors.grey[100],
),
),
],
shape: RoundedRectangleBorder(side: BorderSide(width: 16.0, color: Colors.red.shade100)),
backgroundColor: Colors.lightBlue.shade100,
);
});
}
createAlertDialougeTwo(BuildContext context){
return showDialog(context: context, builder: (context){
return AlertDialog(
title: Text('Not Complete'),
content: Text('Please score 35 and above mark'),
actions: [
Center(
child: RaisedButton(
onPressed: (){Navigator.of(context).pop();},
color: Colors.grey[100],
),
),
],
shape: RoundedRectangleBorder(side: BorderSide(width: 16.0, color: Colors.red.shade100)),
backgroundColor: Colors.lightBlue.shade100,
);
});
}
int mark = 0 ;
_QuizHomeState(this.mark);
String langname;
bool isComplete = false;
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
List <String> images = [
'assets/Ba.gif',
'assets/GA.PNG',
'assets/HA.PNG',
'assets/SA.PNG'
];
return Scaffold(
appBar: AppBar(
title: Text('Quiz Home '),
),
body:ListView(
children: <Widget>[
FlatButton(
child: CustomCard('Easy Round', images[0], des[1], isComplete, Colors.green, mark),
onPressed: () {
{ Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson("Easy Round", mark = 5),
));}
}
),
SizedBox(
height: 20.0,
),
FlatButton(
child: CustomCard('Average Round', images[1], des[1], isComplete, lockOrNot, mark),
onPressed: _onPressedOne,
),
SizedBox(
height: 20.0,
),
FlatButton(
onPressed: _onPressedTwo,
child: CustomCard('Hard Round', images[2],des[2], isComplete, btncolor, mark)
),
SizedBox(
height: 20.0,
),
FlatButton(
onPressed: _onPressedThree,
child: CustomCard('Intermediate Round', images[3],des[3], isComplete, btncolor, mark )
),
],
)
);
}
List <String> des = [
"The easy round lets you test your knowledge in determining letters. Are you up for the challenge? Click here!!!",
"Do you want to step up your baybayin game? Let's see if you can distinguish words! Click here!!!",
"Do you know how to construct sentences with the use of Baybayin? Click here!!!",
"Masters of baybayin can only enter this quiz! Are you one of them? Click Here!!!",
];
Color btncolor;
Widget CustomCard(String roundName,images,String des, bool isComplete, Color btncolor, int mark ) {
return Material(
color: btncolor,
elevation: 10.0,
borderRadius: BorderRadius.circular(20.0),
child: Container(
child: Column(
children: <Widget>[
Text(
'$mark'
),
Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
),
child: Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(100.0),
child: Container(
height: 200.0,
width: 200.0,
child:ClipOval(
child: Image(
image: AssetImage(images),
),
)
),
),
),
Center(
child: Text( roundName,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
letterSpacing: 10.0,
fontFamily: 'S'
),),
),
Container(
padding:EdgeInsets.all(8.0),
child: Text(
des,
style: TextStyle(
color: Colors.white,
letterSpacing: 1.0
),
),
),
],
),
),
);
}
Color unlockColor = Colors.green;
Color lockColor = Colors.grey;
Color lockOrNot = Colors.grey;
void _onPressedOne() {
int marks1 = 24;
if(marks1< mark){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson( "Average Round", 7 ),
));
}
else{
createAlertDialouge(context);
}
}
void _onPressedTwo() {
int marks2 = 34;
int marc = mark;
if( marks2 < marc ){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson("Hard Round", 7 ),
));
}
else{
createAlertDialougeOne(context);
}
}
void _onPressedThree() {
int marks3 = 49;
int marc = mark;
if( marks3 < marc ){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson("Average Round", 8),
));
}
else{
createAlertDialougeTwo(context);
}
}
}
If you need the Result page:
import 'package:baybay_app/Quiz/QuizHome.dart';
import 'package:flutter/material.dart';
class ResultPage extends StatefulWidget {
int mark;
ResultPage({Key key, #required this.mark}) : super(key: key);
#override
_ResultPageState createState() => _ResultPageState(mark);
}
class _ResultPageState extends State<ResultPage> {
List<String> images = [
'assets/excellent.jpg',
'assets/good.png',
'assets/Sorry.png'
];
String message;
String image;
#override
void initState(){
if(mark<5){
image = images[2];
message = 'Try Again..\n' + 'You scored $mark';
}
else if(mark==5){
image = images[1];
message = 'Good.. \n' + 'You scored $mark';
}
else{
image = images[0];
message = 'Excellent!!!...\n' + 'You scored $mark';
}
}
int mark;
_ResultPageState(this.mark);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Result"
)
),
body: Column(
children:[
Expanded(
flex: 6,
child: Material(
elevation: 5.0,
child: Container(
child:Column(
children: [
Material(
child: Container(
width: 300.0,
height: 300.0,
child: ClipRect(
child: Image(
image: AssetImage(
image,
)
)
),
),
),
Center(
child: Text(
message,
style: TextStyle(
fontSize: 20.0,
fontFamily: 'Staatliches'
),
),
)
],
),
),
),
),
Expanded(
flex:4,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
OutlineButton(
onPressed: () {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> QuizHome(mark:mark)));
},
child: Text(
'Continue',
style: TextStyle(
fontSize: 20.0,
fontFamily: 'Staatliches'
)
),
padding: EdgeInsets.symmetric(vertical: 10.0,horizontal: 15.0),
borderSide: BorderSide(width: 3.0,color: Colors.brown[700])
)
],
)
)
]
)
);
}
}
What can I try next?
I am trying to control my switch by getting value from firebase database. Its listening to the value whenever it is changed but i dont understand how to use that value to toggle the button. This is basically an app in which you can control the hardware switch via app and app via hardware with firebase as a bridge between them.
child: LiteRollingSwitch(
value: state,
textOn: 'active',
textOff: 'inactive',
colorOn: Colors.lightGreen,
colorOff: Colors.deepOrange,
iconOn: Icons.lightbulb_outline,
iconOff: Icons.power_settings_new,
onChanged: (bool value) async{
print('turned ${(value) ? 'on' : 'off'}');
final databasereference2 = FirebaseDatabase.instance.reference();
final FirebaseAuth _auth=FirebaseAuth.instance;
final FirebaseUser user = await _auth.currentUser();
final uid = user.uid;
final username=user.email;
var currDt = DateTime.now();
if(value==true)
{
databasereference2.child('users').child(uid).child('Activity log').child('2020').child(currDt.month.toString()).child('day'+currDt.day.toString()).push().set({'state': 'on','switch id':'bed bulb','time':currDt.hour.toString()+':'+currDt.minute.toString()+':'+currDt.second.toString()});
databasereference2.child('users').child(uid).child('Live Status').child('bedroom').child('bedbulb').set('on');
}
else{databasereference2.child('users').child(uid).child('Activity log').child('2020').child(currDt.month.toString()).child('day'+currDt.day.toString()).push().set({'state': 'on','switch id':'bed bulb','time':currDt.hour.toString()+':'+currDt.minute.toString()+':'+currDt.second.toString()});
databasereference2.child('users').child(uid).child('Live Status').child('bedroom').child('bedbulb').set('off');}
The part where i am listening is:
databasereference2.child('users').child(uid).child('Live Status').child('bedroom').onValue.listen((event) {
var snapshot = event.snapshot;
var x = snapshot.value['bedbulb'];
print(x);
if (x == 'on') {setState(() {
value=true;
print(value);
state=value;
print(state);
});
}
else{
setState(() {
value=false;
print(value);
state=value;
print(state);
});
}
}
);
},
),
Please help me in using the value listened to toggle the button. This toggle switch is from flutter library LiteRollingSwitch and its code is here:
library lite_rolling_switch;
import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:math';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/widgets.dart';
class LiteRollingSwitch extends StatefulWidget {
#required
final bool value;
#required
final Function(bool) onChanged;
final String textOff;
final String textOn;
final Color colorOn;
final Color colorOff;
final double textSize;
final Duration animationDuration;
final IconData iconOn;
final IconData iconOff;
final Function onTap;
final Function onDoubleTap;
final Function onSwipe;
final Function toggleswitch;
LiteRollingSwitch(
{this.value = false,
this.textOff = "Off",
this.textOn = "On",
this.textSize = 14.0,
this.colorOn = Colors.green,
this.colorOff = Colors.red,
this.iconOff = Icons.flag,
this.iconOn = Icons.check,
this.animationDuration = const Duration(milliseconds: 600),
this.onTap,
this.onDoubleTap,
this.onSwipe, this.toggleswitch,
this.onChanged});
#override
_RollingSwitchState createState() => _RollingSwitchState();
}
class _RollingSwitchState extends State<LiteRollingSwitch>
with SingleTickerProviderStateMixin {
AnimationController animationController;
Animation<double> animation;
double value = 0.0;
final databasereference2 = FirebaseDatabase.instance.reference();
bool turnState;
#override
void dispose() {
animationController.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
lowerBound: 0.0,
upperBound: 1.0,
duration: widget.animationDuration);
animation =
CurvedAnimation(parent: animationController, curve: Curves.easeInOut);
animationController.addListener(() {
setState(() {
value = animation.value;
});
});
turnState = widget.value;
_determine();
}
#override
Widget build(BuildContext context) {
Color transitionColor = Color.lerp(widget.colorOff, widget.colorOn, value);
return GestureDetector(
onDoubleTap: () {
_action();
if (widget.onDoubleTap != null) widget.onDoubleTap();
},
onTap: () {
_action();
if (widget.onTap != null) widget.onTap();
},
onPanEnd: (details) {
_action();
if (widget.onSwipe != null) widget.onSwipe();
//widget.onSwipe();
},
child: Container(
padding: EdgeInsets.all(5),
width: 130,
decoration: BoxDecoration(
color: transitionColor, borderRadius: BorderRadius.circular(50)),
child: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(10 * value, 0), //original
child: Opacity(
opacity: (1 - value).clamp(0.0, 1.0),
child: Container(
padding: EdgeInsets.only(right: 10),
alignment: Alignment.centerRight,
height: 40,
child: Text(
widget.textOff,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: widget.textSize),
),
),
),
),
Transform.translate(
offset: Offset(10 * (1 - value), 0), //original
child: Opacity(
opacity: value.clamp(0.0, 1.0),
child: Container(
padding: EdgeInsets.only(/*top: 10,*/ left: 5),
alignment: Alignment.centerLeft,
height: 40,
child: Text(
widget.textOn,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: widget.textSize),
),
),
),
),
Transform.translate(
offset: Offset(80 * value, 0),
child: Transform.rotate(
angle: lerpDouble(0, 2 * pi, value),
child: Container(
height: 40,
width: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
shape: BoxShape.circle, color: Colors.white),
child: Stack(
children: <Widget>[
Center(
child: Opacity(
opacity: (1 - value).clamp(0.0, 1.0),
child: Icon(
widget.iconOff,
size: 25,
color: transitionColor,
),
),
),
Center(
child: Opacity(
opacity: value.clamp(0.0, 1.0),
child: Icon(
widget.iconOn,
size: 21,
color: transitionColor,
))),
],
),
),
),
)
],
),
),
);
}
_action() {
_determine(changeState: true);
}
_determine({bool changeState = false}) {
setState(() {
if (changeState) turnState = !turnState;
(turnState)
? animationController.forward()
: animationController.reverse();
widget.onChanged(turnState);
});
}
}
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qrscan/qrscan.dart' as scanner;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.grey[300],
body: Builder(
builder: (BuildContext context) {
return ListView(
children: <Widget>[
_qrCodeWidget(this.bytes, context),
Container(
color: Colors.white,
child: Column(
children: <Widget>[
TextField(
controller: this._inputController,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.go,
onSubmitted: (value) => _generateBarCode(value),
decoration: InputDecoration(
prefixIcon: Icon(Icons.text_fields),
helperText: 'Please input your code to generage qrcode image.',
hintText: 'Please Input Your Code',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
TextField(
controller: this._outputController,
maxLines: 2,
decoration: InputDecoration(
prefixIcon: Icon(Icons.wrap_text),
helperText: 'The barcode or qrcode you scan will be displayed in this area.',
hintText: 'The barcode or qrcode you scan will be displayed in this area.',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
this._buttonGroup(),
SizedBox(height: 70),
],
),
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scanBytes(),
tooltip: 'Take a Photo',
child: const Icon(Icons.camera_alt),
),
),
);
}
Widget _qrCodeWidget(Uint8List bytes, BuildContext context) {
return Padding(
padding: EdgeInsets.all(20),
child: Card(
elevation: 6,
child: Column(
children: <Widget>[
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Icon(Icons.verified_user, size: 18, color: Colors.green),
Text(' Generate Qrcode', style: TextStyle(fontSize: 15)),
Spacer(),
Icon(Icons.more_vert, size: 18, color: Colors.black54),
],
),
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 9),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4), topRight: Radius.circular(4)),
),
),
Padding(
padding: EdgeInsets.only(
left: 40, right: 40, top: 30, bottom: 10),
child: Column(
children: <Widget>[
SizedBox(
height: 190,
child: bytes.isEmpty
? Center(
child: Text('Empty code ... ',
style: TextStyle(color: Colors.black38)),
)
: Image.memory(bytes),
),
Padding(
padding: EdgeInsets.only(top: 7, left: 25, right: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
flex: 5,
child: GestureDetector(
child: Text(
'remove',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.left,
),
onTap: () =>
this.setState(() => this.bytes = Uint8List(0)),
),
),
Text('|', style: TextStyle(fontSize: 15, color: Colors
.black26)),
Expanded(
flex: 5,
child: GestureDetector(
onTap: () async {
final success = await ImageGallerySaver.saveImage(
this.bytes);
SnackBar snackBar;
if (success) {
snackBar = new SnackBar(content: new Text(
'Successful Preservation!'));
Scaffold.of(context).showSnackBar(snackBar);
} else {
snackBar =
new SnackBar(content: new Text('Save failed!'));
}
},
child: Text(
'save',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.right,
),
),
),
],
),
)
],
),
),
Divider(height: 2, color: Colors.black26),
],
),
),
);
}
Widget _buttonGroup() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: () => _generateBarCode(this._inputController.text),
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/generate_qrcode.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Generate")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scan,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/scanner.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scanPhoto,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/albums.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan Photo")),
],
),
),
),
),
),
],
);
}
Future _scan() async {
String barcode = await scanner.scan();
if (barcode == null) {
print('nothing return.');
} else {
this._outputController.text = barcode;
}
}
Future _scanPhoto() async {
String barcode = await scanner.scanPhoto();
this._outputController.text = barcode;
}
Future _scanPath(String path) async {
String barcode = await scanner.scanPath(path);
this._outputController.text = barcode;
}
Future _scanBytes() async {
File file = await ImagePicker.pickImage(source: ImageSource.camera);
Uint8List bytes = file.readAsBytesSync();
String barcode = await scanner.scanBytes(bytes);
this._outputController.text = barcode;
}
Future _generateBarCode(String inputCode) async {
Uint8List result = await scanner.generateBarCode(inputCode);
this.setState(() => this.bytes = result);
}
}
class MyAppState extends State<MyApp> {
Future<SharedPreferences> _sPrefs = SharedPreferences.getInstance();
final TextEditingController controller = TextEditingController();
List<String> listOne, listTwo;
#override
void initState() {
super.initState();
listOne = [];
listTwo = [];
}
Future<Null> addString() async {
final SharedPreferences prefs = await _sPrefs;
listOne.add(controller.text);
prefs.setStringList('list', listOne);
setState(() {
controller.text = '';
});
}
Future<Null> clearItems() async {
final SharedPreferences prefs = await _sPrefs;
prefs.clear();
setState(() {
listOne = [];
listTwo = [];
});
}
Future<Null> getStrings() async {
final SharedPreferences prefs = await _sPrefs;
listTwo = prefs.getStringList('list');
setState(() {});
}
Future<Null> updateStrings(String str) async {
final SharedPreferences prefs = await _sPrefs;
setState(() {
listOne.remove(str);
listTwo.remove(str);
});
prefs.setStringList('list', listOne);
}
#override
Widget build(BuildContext context) {
getStrings();
return Center(
child: ListView(
children: <Widget>[
TextField(
controller: controller,
decoration: InputDecoration(
hintText: 'Type in something...',
)),
RaisedButton(
child: Text("Submit"),
onPressed: () {
addString();
},
),
RaisedButton(
child: Text("Clear"),
onPressed: () {
clearItems();
},
),
Flex(
direction: Axis.vertical,
children: listTwo == null
? []
: listTwo
.map((String s) => Dismissible(
key: Key(s),
onDismissed: (direction) {
updateStrings(s);
},
child: ListTile(
title: Text(s),
)))
.toList(),
)
],
),
);
}
}
Here the first Appstate creates a Qr code reader. Second is for creating an input controller with shared preferences that can store and retrieve data locally. But when running the code the app displays only the qrscan part and 2nd is not working. I'm new to Flutter. I've just started working on Android Studio. Can anybody help please?
Try to call Another class from home property of the MyApp class.
As you can see in this image
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
//Here I have called MyWidget Class
home: MyWidget()
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(