How to access one button at a time? - android

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?

Related

Why does Focus Node not work when disposing and recreating widget?

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);
}
}
}

How to show list of images in grid view builder if list is not empty

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,
),
),
),
);
},
),

The following ArgumentError was thrown building GamePage(dirty, state: _GamePageState#d2e81): Invalid argument(s) on flutter

I get this error and don't know why. can you help me?
I am trying to use different lists in the app by users choices. but I get this error when I start the app
Here is the main file
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'story_brain.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
//pride or insult
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: GamePage(),
);
}
}
class FirstScreen extends StatelessWidget {
Widget build(BuildContext context2) {
return MaterialApp(
home: FirstScreenMaterialApp(),
);
}
}
class FirstScreenMaterialApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.purple[900],
body: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 20, 50),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Image(
image: AssetImage("assets/images/logo.png"),
width: 000,
height: 400,
),
Expanded(
child: FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => GamePage()),
);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
color: Colors.lightBlue,
child: Center(
child: Text(
"Klasik",
style: TextStyle(fontSize: 40),
),
),
),
),
SizedBox(
height: 20,
),
Expanded(
child: FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => GamePage()),
);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
color: Colors.red,
child: Center(
child: Text(
"Temel içgüdü(+18)",
style: TextStyle(fontSize: 40),
),
),
),
),
],
),
),
),
);
}
}
class GamePage extends StatefulWidget {
_GamePageState createState() => _GamePageState();
}
class _GamePageState extends State<GamePage> {
StoryBrain storyBrain = StoryBrain();
Widget build(BuildContext context) {
return Center(
child: Scaffold(
body: Container(
color: Colors.purple[800],
padding: EdgeInsets.symmetric(vertical: 50.0, horizontal: 30.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Expanded(
flex: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 0,
child: Icon(
Icons.whatshot,
size: 70,
color: storyBrain.changeHeatBarColor(),
),
),
Expanded(
flex: 1,
child: Text(
storyBrain.updateHeat(),
style: TextStyle(
fontSize: 50,
fontFamily: "CustomFamilyName",
color: storyBrain.changeHeatBarColor(),
),
),
)
],
),
),
Center(
child: Expanded(
flex: 100,
child: Center(
child: Container(
padding: EdgeInsets.all(20),
margin: EdgeInsets.fromLTRB(20, 0, 20, 60),
width: 300,
height: 250,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: storyBrain.setColor(),
),
child: Text(
storyBrain.getText(),
style: TextStyle(
fontSize: 30.0,
),
),
),
),
),
),
Expanded(
flex: 10,
child: FlatButton(
onPressed: () {
storyBrain.changeNumber();
setState(() {
storyBrain.getText();
storyBrain.setColor();
storyBrain.changeHeatBarColor();
storyBrain.updateHeat();
});
},
color: storyBrain.setColor(),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
child: Center(
child: Text(
"Değiştir",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
),
),
),
),
),
SizedBox(
height: 20,
)
],
),
),
),
);
}
}
story_brain file:
import 'package:flutter/material.dart';
import 'story.dart';
import 'dart:math';
class StoryBrain {
static Random random = Random();
int textNumber;
bool gameTypeIsClasic = false;
static List<Story> textListClasic = [
Story(
"text content 2",
"göm",
),
Story(
"text content 1",
"öv",
),
Story(
"text content 3",
"göm",
),
Story("text content 4", "öv")
];
static List<Story> textListTemel = [
Story(
"text content 1",
"göm",
),
Story(
"text content 2",
"öv",
),
Story(
"text content 3",
"göm",
),
Story("text content 4", "öv")
];
int heat = 1;
StoryBrain() {
if (gameTypeIsClasic == true) {
random.nextInt(textListClasic.length - 1);
} else {
random.nextInt(textListTemel.length - 1);
}
}
void changeNumber() {
if (gameTypeIsClasic == true) {
textNumber = random.nextInt(textListClasic.length - 1);
} else {
textNumber = random.nextInt(textListTemel.length - 1);
}
}
String getText() {
if (gameTypeIsClasic == true) {
return textListClasic[textNumber].textContent;
} else {
return textListTemel[textNumber].textContent;
}
}
String getTextType() {
if (gameTypeIsClasic == true) {
return textListClasic[textNumber].textType;
} else {
return textListTemel[textNumber].textType;
}
}
Color setColor() {
if (getTextType() == "öv") {
return Colors.blue;
} else {
return Colors.red;
}
}
String updateHeat() {
if (getTextType() == "öv") {
if (heat > 1 && heat < 20) {
heat = heat - 1;
} else if (heat > 20 && heat < 100) {
heat -= 10;
} else if (heat > 200 && heat < 500) {
heat -= 25;
} else if (heat > 500) {
heat = (heat ~/ 3);
} else {
heat = heat;
}
} else {
if (heat < 1000) {
heat = heat * 2;
} else {
heat += 100;
}
}
return heat.toString() + "x";
}
Color changeHeatBarColor() {
if (heat >= 50 && heat < 100) {
return Colors.orange;
} else if (heat >= 100 && heat < 500) {
return Colors.redAccent;
} else if (heat > 500) {
return Colors.red[800];
} else {
return Colors.blue;
}
}
}
You are getting the error because you didn't give the textNumber an initial value and you were using it in other methods definition to access elements from your textListClasic list.
I updated the StoryBrain class to set an initial value for the textNumber variable:
class StoryBrain {
static Random random = Random();
// initialize the textNumber variable
int textNumber = 0; // new line
bool gameTypeIsClasic = false;
static List<Story> textListClasic = [
Story(
"text content 2",
"göm",
),
Story(
"text content 1",
"öv",
),
Story(
"text content 3",
"göm",
),
Story("text content 4", "öv")
];
... // remaining codes
}

How to refresh the main page after opening a page from an android drawer menu with Flutter

I have a problem, I have a main activity where I have loaded several widget classes so far so good.
now what I want to do is refresh the main page after closing a page that has been triggered in a Drawer menu.
It works if the button is directly on the main page, but if the action is triggered from the Drawer menu it does not work.
Example of screen or it works very well
Option 2
It should look like this. but it doesn't work when I call the page from the Drawer menu
reference link:
How to go back and refresh the previous page in Flutter?
How to refresh a page after back button pressed
Would anyone have an idea.
Here is the code to use for option 1 with the button on the main page:
new RaisedButton(
onPressed: ()=>
Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new PageHomeContent()),)
.then((val)=>{getRefreshRequests()}),
child: Text('Refresh', style: TextStyle(color: Colors.white), ), color: Colors.purple,
elevation: 2.0,
),
It is important to know that I have created a class for the Drawer menu here. it is a little long but I you essential
final Color primaryColor = Colors.white;
final Color activeColor = Colors.grey.shade800;
final Color dividerColor = Colors.grey.shade600;
class BuildDrawer extends StatefulWidget{
#override
_BuildDrawer createState() => _BuildDrawer();
}
class _BuildDrawer extends State<BuildDrawer> {
//region [ ATTRIUTS ]
final String image = 'https://avatars2.githubusercontent.com/u/3463865?s=460&u=c0fab43e4b105e9745dc3b5cf61e21e79c5406c2&v=4';
List<dynamic> menuGroupList = [];
Future<List<dynamic>> _futureMenuGroupList;
bool _infiniteStop;
//MenuItemGroupModel menuItemGroup = new MenuItemGroupModel();
List<dynamic> menuItemList = [];
Future<List<dynamic>> _futureMenuItemList;
//Future<MenuItemGroupModel> _futureMenuItemGroup;
bool _infiniteItemStop;
//endregion
#override
void initState() {
_futureMenuGroupList = fetchMenuWPList();
_infiniteStop = false;
}
#override
Widget build(BuildContext context) {
return ClipPath(
clipper: OvalRightBorderClipper(),
child: Drawer(
child: Container(
padding: const EdgeInsets.only(left: 16.0, right: 40),
decoration: BoxDecoration(
color: primaryColor,
boxShadow: [BoxShadow(color: Colors.black45)]),
width: 300,
child: SafeArea(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: InkWell(
onTap: () {
//Navigator.push( context, MaterialPageRoute(builder: (context) => PageHomeContent(),),);
Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new PageHomeContent()),)
.then((val)=>{ new MainPage() });
},
child:
Column(
children: <Widget>[
Row(
children: [
Icon(
Icons.format_list_bulleted,
color: activeColor,
),
SizedBox(width: 10.0),
Text("Home Content", ),
Spacer(),
]
),
],
),
),
),
Divider(
color: dividerColor,
),
],
),
),
),
),
),
);
}
}
//end Class
//region [ MENU ITEM PAGE ]
//endregion
Main Page Class [ MainPage ]
class MainPage extends StatefulWidget {
//MainPage({Key key, this.title}): super(key: key);
//final String title;
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<WPMainPage> {
//region [ ATTRIBUTS ]
List<dynamic> featuredArticles = [];
List<dynamic> latestArticles = [];
List<dynamic> pageList = [];
List<dynamic> menuGroupList = [];
List<dynamic> categoryHomeList = [];
Future<List<dynamic>> _futurePageList;
Future<List<dynamic>> _futureFeaturedArticles;
Future<List<dynamic>> _futureLastestArticles;
Widget widgetCategoryBuilder=new Container();
final _categoryRepository = CategoryRepository();
ScrollController _controller;
int page = 1;
bool _showLoadingPage = true;
bool _showLoadingCategoryHome = true;
bool _infiniteStop;
double heightNoInternet = 280.0;
// Firebase Cloud Messeging setup
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
//endregion
#override
void initState() {
super.initState();
_futureFeaturedArticles = fetchFeaturedArticles(1);
_futureLastestArticles = fetchLatestArticles(1);
_futurePageList = fetchPageList();
getCategoriesOnLocal();
_controller = ScrollController(initialScrollOffset: 0.0, keepScrollOffset: true);
_controller.addListener(_scrollListener);
_infiniteStop = false;
}
#override
void dispose() {
super.dispose();
_controller.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(Constant.APP_NAME_LONG),
actions: getActionAppBarButton(context: context),
),
drawer: BuildDrawer(),
body: Container(
decoration: BoxDecoration(color: Colors.white70),
child: SingleChildScrollView(
controller: _controller,
scrollDirection: Axis.vertical,
child: Column(
children:
getWidgetList()
),
),
));
}
getRefreshRequests() async {
getCategoriesOnLocal();
//Tools.mySnackBar(context, ' m s g TEST 1 ');
}
getWidgetList() {
List<Widget> itemList = new List<Widget>();
itemList.add(
new Column(
children: <Widget>[
new RaisedButton(
onPressed: ()=>
Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new PageHomeContent()),)
.then((val)=>{ getRefreshRequests() }),
child: Text('Refresh', style: TextStyle(color: Colors.white), ), color: Colors.purple,
elevation: 2.0,
),
],
)
);
itemList.add(
getPagebuilderList(isShowTitle: false)
);
itemList.add(
featuredPostBuildSlider(_futureFeaturedArticles)
);
/*itemList.add(
featuredPost(_futureFeaturedArticles),
);*/
itemList.add(
widgetCategoryBuilder
);
itemList.add(
latestPosts(_futureLastestArticles)
);
return itemList;
}
_scrollListener() {
var isEnd = _controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange;
if (isEnd) {
setState(() {
page += 1;
_futureLastestArticles = fetchLatestArticles(page);
});
}
}
//region [ ALL POST | RECENTS POST ]
//endregion
//region [ POST FEATURED | Swiper ]
//endregion
//region [ PAGES ]
//endregion
//region [ CATEGORIES LOCAL --> ON LIGNE ]
void getCategoriesOnLocal() async {
try {
await _categoryRepository.getCategories().then((itemList) {
if (itemList != null) {
setState(() {
categoryHomeList = itemList;
});
getCategoryBuilder();
}
});
} catch (e) {
Tools.println("Error: getCategoriesOnLocal: $e");
}
}
getCategoryBuilder() {
List<Widget> itemWidgetList=[];
if( _showLoadingCategoryHome) {
if (categoryHomeList.length > 0) {
for (Category category in categoryHomeList) {
if (category.count > 0) {
itemWidgetList.add(
getItemArticle(category: category)
);
}
}
widgetCategoryBuilder= Column( children: itemWidgetList );
} else {
widgetCategoryBuilder= Container();
}
} else {
widgetCategoryBuilder= Container();
}
setState(() {
widgetCategoryBuilder = widgetCategoryBuilder;
});
return widgetCategoryBuilder;
}
Widget getItemArticle({Category category}) {
return
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 8.0, right: 8.0),
child: Row(
children: <Widget>[
Text('${category.name}',
style: homeTitleTextStyle,
textAlign: TextAlign.left,),
Spacer(),
InkWell(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CategoryArticles(category.id, category.name),
),
);
},
child: Text('See More',
textAlign: TextAlign.right,
style: TextStyle(color: Colors.red),),
),
],),
),
new CategoryHomeBuilder( categorieId: category.id),
],
);
}
//endregion
}
Does anyone have a suggestion.
Thanks for your help
Waiting for a better response.
I replaced the BuildDrawer class with a getBuildDrawer() method in the main class.
And it works very well but I would have preferred to put it in a separate class, so that I can use it in another page ...
getBuildDrawer() {
return ClipPath(
clipper: OvalRightBorderClipper(),
child: Drawer(
child: Container(
padding: const EdgeInsets.only(left: 16.0, right: 40),
decoration: BoxDecoration(
color: primaryColor,
boxShadow: [BoxShadow(color: Colors.black45)]),
width: 300,
child: SafeArea(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: InkWell(
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new PageHomeContent()),)
.then((val)=>{ getRefreshRequests() });
},
child:
Column(
children: <Widget>[
Row(
children: [
Icon(
Icons.format_list_bulleted,
color: activeColor,
),
SizedBox(width: 10.0),
Text("Home Content", ),
Spacer(),
]
),
],
),
),
),
Divider(
color: dividerColor,
),
],
),
),
),
),
),
);
}
you have to refresh the page just putting setState(getRefreshRequests()) when you return from navigator, that's because the page don't know that you put a new widget on screen

How Create SearchView in List Flutter

i need yur advice .
I Have code to fetch data from api to ListView .
The question is , how to create searchview in this listview .
class PM extends StatefulWidget {
#override
_PMState createState() => _PMState();
}
class _PMState extends State<PM> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
void showInSnackBar(String value) {
_scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text(value),
backgroundColor: Colors.blueAccent,
));
}
final GlobalKey<RefreshIndicatorState> _refresh =
GlobalKey<RefreshIndicatorState>();
ModelPM modelPM;
ModelPM _modelPM;
bool loading = false;
Future<Null> _fetchData() async {
setState(() => loading = true);
var value;
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
value = preferences.getString("id");
});
final response = await http.post(BaseURL.systemTicket, body: {
"key": BaseURL.apiKey,
"method": "get",
"resource": "tabel_pm",
"filters[adminidtabelpm]": value,
});
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final pmModelFromJson = ModelPM.fromJson(data);
setState(() {
modelPM = pmModelFromJson;
loading = false;
});
} else {
showInSnackBar("Data Gagal Load");
}
}
#override
void initState() {
super.initState();
_fetchData();
}
_listPM(i) {
final x = modelPM.results[i];
return Card(
elevation: 8.0,
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
child: ListTile(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => DetilPM(x, _fetchData)));
},
contentPadding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
x.name,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 12,
color: x.status == "Not Yet"
? Colors.blue
: x.status == "Pending" ? Colors.red : Colors.green,
fontWeight: FontWeight.bold),
),
Text(
'Status : ' + x.status,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 12,
color: x.status == "Not Yet"
? Colors.blue
: x.status == "Pending" ? Colors.red : Colors.green,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
],
),
subtitle: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text("MIDTID",
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text("TID",
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text("CSI",
style: TextStyle(color: Colors.black, fontSize: 10))),
),
],
),
Row(
children: <Widget>[
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text(x.midtid,
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text(x.tid,
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text(x.csi,
style: TextStyle(color: Colors.black, fontSize: 10))),
),
],
)
],
),
trailing:
Icon(Icons.keyboard_arrow_right, color: Colors.black, size: 30.0),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('PM CIMB List'),
),
key: _scaffoldKey,
body: RefreshIndicator(
onRefresh: _fetchData,
key: _refresh,
child: loading
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: modelPM.results.length,
itemBuilder: (context, i) {
return _listPM(i);
},
),
),
);
}
}
and below this model class PM .
class ModelPM {
final int status;
final String status_message;
final List<ModelPMResult> results;
ModelPM({this.status, this.status_message, this.results});
factory ModelPM.fromJson(Map<String, dynamic> json) {
List<ModelPMResult> results = (json['result'] as List)
.map((resultTicketJson) => ModelPMResult.fromJson(resultTicketJson))
.toList();
return ModelPM(
status: json['status'],
status_message: json['status_message'],
results: results,
);
}
}
class ModelPMResult {
final String id;
final String admintabelpm;
final String namaitfs;
final String serial;
final String merchantid;
final String assetid;
final String kondisi_edc;
final String status;
final String detail_edc;
final String note;
final String foto_struk;
final String foto_mesin;
final String foto_toko;
final String kondisi_merchant;
final String request_merchant;
final String tgl_pm;
final String name;
final String batch;
final String idmerchant;
final String midtid;
final String tid;
final String csi;
final String sign;
ModelPMResult({
this.id,
this.admintabelpm,
this.namaitfs,
this.serial,
this.merchantid,
this.assetid,
this.kondisi_edc,
this.status,
this.detail_edc,
this.kondisi_merchant,
this.request_merchant,
this.tgl_pm,
this.name,
this.batch,
this.idmerchant,
this.midtid,
this.tid,
this.csi,
this.foto_mesin,
this.foto_struk,
this.foto_toko,
this.note,
this.sign,
});
factory ModelPMResult.fromJson(Map<String, dynamic> json) {
return new ModelPMResult(
id: json['id'],
admintabelpm: json['id'],
namaitfs: json['namaitfs'],
serial: json['serial'],
merchantid: json['merchantid'],
assetid: json['assetid'],
kondisi_edc: json['kondisi_edc'],
status: json['status'],
detail_edc: json['detail_edc'],
kondisi_merchant: json['kondisi_merchant'],
request_merchant: json['request_merchant'],
tgl_pm: json['tgl_pm'],
name: json['name'],
batch: json['batch'],
idmerchant: json['idmerchant'],
midtid: json['midtid'],
tid: json['tid'],
csi: json['csi'],
note: json['note'],
foto_mesin: json['foto_mesin'],
foto_toko: json['foto_toko'],
foto_struk: json['foto_struk'],
sign: json['sign'],
);
}
}
Please advice for , how to create listview menu in my Page Flutter .
Thanks for your advice .
and also how after the data is deleted in the search menu, data from the API returns to the list
Two solutions : you can copy paste run full code below
Solution 1 : Search use current ListView page, In itemBuilder return data only fit your condition, such as string contains, if not return Container()
ListView.builder(
itemCount: modelPM.results.length,
itemBuilder: (context, i) {
if (myController.text == "") return _listPM(i);
if (myController.text != "" &&
modelPM.results[i].tid.contains(myController.text)) {
return _listPM(i);
} else {
return Container();
}
},
),
demo 1
full code 1
import 'package:flutter/material.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: PM(),
);
}
}
class PM extends StatefulWidget {
#override
_PMState createState() => _PMState();
}
class _PMState extends State<PM> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
void showInSnackBar(String value) {
_scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text(value),
backgroundColor: Colors.blueAccent,
));
}
final GlobalKey<RefreshIndicatorState> _refresh =
GlobalKey<RefreshIndicatorState>();
ModelPM modelPM;
ModelPM _modelPM;
bool loading = false;
Future<Null> _fetchData() async {
setState(() => loading = true);
var value;
/*SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
value = preferences.getString("id");
});
final response = await http.post(BaseURL.systemTicket, body: {
"key": BaseURL.apiKey,
"method": "get",
"resource": "tabel_pm",
"filters[adminidtabelpm]": value,
});*/
/* if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final pmModelFromJson = ModelPM.fromJson(data);
setState(() {
modelPM = pmModelFromJson;
loading = false;
});
} else {
showInSnackBar("Data Gagal Load");
}*/
String responsebody = '''
{
"status": 200,
"status_message" : "OK",
"result" : [
{
"id": "123",
"name" : "name1",
"notes" : "notes1",
"midtid" : "midtid1",
"tid" : "tid1",
"csi" : "csi1",
"status" : "abc"
}
,
{
"id": "456",
"name" : "name2",
"notes" : "notes2",
"midtid" : "midtid2",
"tid" : "tid2",
"csi" : "csi2",
"status" : "def"
}
]
}
''';
final data = jsonDecode(responsebody);
final pmModelFromJson = ModelPM.fromJson(data);
setState(() {
modelPM = pmModelFromJson;
loading = false;
});
}
#override
void initState() {
super.initState();
_fetchData();
}
_listPM(i) {
final x = modelPM.results[i];
return Card(
elevation: 8.0,
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
child: ListTile(
onTap: () {
/*Navigator.of(context).push(
MaterialPageRoute(builder: (context) => DetilPM(x, _fetchData)));*/
},
contentPadding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
x.name,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 12,
color: x.status == "Not Yet"
? Colors.blue
: x.status == "Pending" ? Colors.red : Colors.green,
fontWeight: FontWeight.bold),
),
Text(
'Status : ' + x.status,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 12,
color: x.status == "Not Yet"
? Colors.blue
: x.status == "Pending" ? Colors.red : Colors.green,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
],
),
subtitle: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text("MIDTID",
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text("TID",
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text("CSI",
style: TextStyle(color: Colors.black, fontSize: 10))),
),
],
),
Row(
children: <Widget>[
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text(x.midtid,
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text(x.tid,
style: TextStyle(color: Colors.black, fontSize: 10))),
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 0.0),
child: Text(x.csi,
style: TextStyle(color: Colors.black, fontSize: 10))),
),
],
)
],
),
trailing:
Icon(Icons.keyboard_arrow_right, color: Colors.black, size: 30.0),
),
);
}
final myController = TextEditingController();
#override
void dispose() {
// Clean up the controller when the widget is removed from the
// widget tree.
myController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
controller: myController,
decoration:
InputDecoration(border: InputBorder.none, hintText: 'Search'),
onChanged: (value) {
setState(() {});
},
),
),
key: _scaffoldKey,
body: RefreshIndicator(
onRefresh: _fetchData,
key: _refresh,
child: loading
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: modelPM.results.length,
itemBuilder: (context, i) {
if (myController.text == "") return _listPM(i);
if (myController.text != "" &&
modelPM.results[i].tid.contains(myController.text)) {
return _listPM(i);
} else {
return Container();
}
},
),
),
);
}
}
class ModelPM {
final int status;
final String status_message;
final List<ModelPMResult> results;
ModelPM({this.status, this.status_message, this.results});
factory ModelPM.fromJson(Map<String, dynamic> json) {
List<ModelPMResult> results = (json['result'] as List)
.map((resultTicketJson) => ModelPMResult.fromJson(resultTicketJson))
.toList();
return ModelPM(
status: json['status'],
status_message: json['status_message'],
results: results,
);
}
}
class ModelPMResult {
final String id;
final String admintabelpm;
final String namaitfs;
final String serial;
final String merchantid;
final String assetid;
final String kondisi_edc;
final String status;
final String detail_edc;
final String note;
final String foto_struk;
final String foto_mesin;
final String foto_toko;
final String kondisi_merchant;
final String request_merchant;
final String tgl_pm;
final String name;
final String batch;
final String idmerchant;
final String midtid;
final String tid;
final String csi;
final String sign;
ModelPMResult({
this.id,
this.admintabelpm,
this.namaitfs,
this.serial,
this.merchantid,
this.assetid,
this.kondisi_edc,
this.status,
this.detail_edc,
this.kondisi_merchant,
this.request_merchant,
this.tgl_pm,
this.name,
this.batch,
this.idmerchant,
this.midtid,
this.tid,
this.csi,
this.foto_mesin,
this.foto_struk,
this.foto_toko,
this.note,
this.sign,
});
factory ModelPMResult.fromJson(Map<String, dynamic> json) {
return new ModelPMResult(
id: json['id'],
admintabelpm: json['id'],
namaitfs: json['namaitfs'],
serial: json['serial'],
merchantid: json['merchantid'],
assetid: json['assetid'],
kondisi_edc: json['kondisi_edc'],
status: json['status'],
detail_edc: json['detail_edc'],
kondisi_merchant: json['kondisi_merchant'],
request_merchant: json['request_merchant'],
tgl_pm: json['tgl_pm'],
name: json['name'],
batch: json['batch'],
idmerchant: json['idmerchant'],
midtid: json['midtid'],
tid: json['tid'],
csi: json['csi'],
note: json['note'],
foto_mesin: json['foto_mesin'],
foto_toko: json['foto_toko'],
foto_struk: json['foto_struk'],
sign: json['sign'],
);
}
}
Solution 2 : Search with SearchDelegate, data actually display in another page
When click search button, open another page
demo
full demo code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: SearchDemo(),
);
}
}
class SearchDemo extends StatefulWidget {
static const String routeName = '/material/search';
#override
_SearchDemoState createState() => _SearchDemoState();
}
class _SearchDemoState extends State<SearchDemo> {
final _SearchDemoSearchDelegate _delegate = _SearchDemoSearchDelegate();
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
int _lastIntegerSelected;
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
leading: IconButton(
tooltip: 'Navigation menu',
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
color: Colors.white,
progress: _delegate.transitionAnimation,
),
onPressed: () {
_scaffoldKey.currentState.openDrawer();
},
),
title: const Text('Numbers'),
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () async {
final int selected = await showSearch<int>(
context: context,
delegate: _delegate,
);
if (selected != null && selected != _lastIntegerSelected) {
setState(() {
_lastIntegerSelected = selected;
});
}
},
),
//MaterialDemoDocumentationButton(SearchDemo.routeName),
IconButton(
tooltip: 'More (not implemented)',
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
),
onPressed: () { },
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
MergeSemantics(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text('Press the '),
Tooltip(
message: 'search',
child: Icon(
Icons.search,
size: 18.0,
),
),
Text(' icon in the AppBar'),
],
),
const Text('and search for an integer between 0 and 100,000.'),
],
),
),
const SizedBox(height: 64.0),
Text('Last selected integer: ${_lastIntegerSelected ?? 'NONE' }.'),
],
),
),
floatingActionButton: FloatingActionButton.extended(
tooltip: 'Back', // Tests depend on this label to exit the demo.
onPressed: () {
Navigator.of(context).pop();
},
label: const Text('Close demo'),
icon: const Icon(Icons.close),
),
drawer: Drawer(
child: Column(
children: <Widget>[
const UserAccountsDrawerHeader(
accountName: Text('Peter Widget'),
accountEmail: Text('peter.widget#example.com'),
currentAccountPicture: CircleAvatar(
backgroundImage: AssetImage(
'people/square/peter.png',
package: 'flutter_gallery_assets',
),
),
margin: EdgeInsets.zero,
),
MediaQuery.removePadding(
context: context,
// DrawerHeader consumes top MediaQuery padding.
removeTop: true,
child: const ListTile(
leading: Icon(Icons.payment),
title: Text('Placeholder'),
),
),
],
),
),
);
}
}
class _SearchDemoSearchDelegate extends SearchDelegate<int> {
final List<int> _data = List<int>.generate(100001, (int i) => i).reversed.toList();
final List<int> _history = <int>[42607, 85604, 66374, 44, 174];
#override
Widget buildLeading(BuildContext context) {
return IconButton(
tooltip: 'Back',
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
},
);
}
#override
Widget buildSuggestions(BuildContext context) {
final Iterable<int> suggestions = query.isEmpty
? _history
: _data.where((int i) => '$i'.startsWith(query));
return _SuggestionList(
query: query,
suggestions: suggestions.map<String>((int i) => '$i').toList(),
onSelected: (String suggestion) {
query = suggestion;
showResults(context);
},
);
}
#override
Widget buildResults(BuildContext context) {
final int searched = int.tryParse(query);
if (searched == null || !_data.contains(searched)) {
return Center(
child: Text(
'"$query"\n is not a valid integer between 0 and 100,000.\nTry again.',
textAlign: TextAlign.center,
),
);
}
return ListView(
children: <Widget>[
_ResultCard(
title: 'This integer',
integer: searched,
searchDelegate: this,
),
_ResultCard(
title: 'Next integer',
integer: searched + 1,
searchDelegate: this,
),
_ResultCard(
title: 'Previous integer',
integer: searched - 1,
searchDelegate: this,
),
],
);
}
#override
List<Widget> buildActions(BuildContext context) {
return <Widget>[
if (query.isEmpty)
IconButton(
tooltip: 'Voice Search',
icon: const Icon(Icons.mic),
onPressed: () {
query = 'TODO: implement voice input';
},
)
else
IconButton(
tooltip: 'Clear',
icon: const Icon(Icons.clear),
onPressed: () {
query = '';
showSuggestions(context);
},
),
];
}
}
class _ResultCard extends StatelessWidget {
const _ResultCard({this.integer, this.title, this.searchDelegate});
final int integer;
final String title;
final SearchDelegate<int> searchDelegate;
#override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return GestureDetector(
onTap: () {
searchDelegate.close(context, integer);
},
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(title),
Text(
'$integer',
style: theme.textTheme.headline.copyWith(fontSize: 72.0),
),
],
),
),
),
);
}
}
class _SuggestionList extends StatelessWidget {
const _SuggestionList({this.suggestions, this.query, this.onSelected});
final List<String> suggestions;
final String query;
final ValueChanged<String> onSelected;
#override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return ListView.builder(
itemCount: suggestions.length,
itemBuilder: (BuildContext context, int i) {
final String suggestion = suggestions[i];
return ListTile(
leading: query.isEmpty ? const Icon(Icons.history) : const Icon(null),
title: RichText(
text: TextSpan(
text: suggestion.substring(0, query.length),
style: theme.textTheme.subhead.copyWith(fontWeight: FontWeight.bold),
children: <TextSpan>[
TextSpan(
text: suggestion.substring(query.length),
style: theme.textTheme.subhead,
),
],
),
),
onTap: () {
onSelected(suggestion);
},
);
},
);
}
}

Categories

Resources