help me pls. I send parameters from page A with this code
onTap: () =>
Navigator.pushNamed(context, 'edit', arguments: {
"id_pet": pid,
"category_pet": pnombre,
}),
And i received them so, i try with this code but it doesnt work for me :
var selectedDropDownValueCat;
#override
void initState() {
super.initState();
/* ---- look this is,here i want initialize the value received from othe page ------- */
//selectedDropDownValue = "New";
selectedDropDownValue = (arguments["category1_pet"]); // it doesnt work :(
}
Widget build(BuildContext context) {
dynamic arguments = ModalRoute.of(context).settings.arguments;
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: Text("Edit"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.photo_size_select_actual),
onPressed: _FotoA,
),
IconButton(
icon: Icon(Icons.camera_alt),
onPressed: _FotoB,
)
],
),
drawer: MenuWidget(),
body: Form(key: formKey, child: _publicarForm(context, arguments)),
);
}
but i want initialize this values in the initState in order to have the value of the other page
Please use this code in initState
Future.delayed(Duration,zero, () {
dynamic arguments = ModalRoute.of(context).settings.arguments;
selectedDropDownValue = (arguments["category_pet"]);
});
Related
I using qr_code_scanner for scan a qr code & barcodes. Its scanning perfectly. But when i want to use dialog after scan for ask how much product did you scan and after that check it and control it.But when i use textfield inside of dialog and when i tap textfield camera stops working and its stays in black screen. What should i do ? What is wrong ? My codes for scan :
void _onQRViewCreated(QRViewController controller) {
this.controller = controller;
controller.scannedDataStream.listen((scanData) {
controller.pauseCamera();
player.play("scanner_sound.mp3");
inspect(args);
if (args.Barcode == scanData.code) {
showDialog(
context: context,
builder: (context) {
return WillPopScope(
onWillPop: () async {
Navigator.pop(context);
controller.resumeCamera();
return true;
},
child: AlertDialog(
title: const Text('Ürün Giriş'),
content: Column(
children: [
const Text('Bu üründen kaç adet okutuldu ?'),
TextField(
keyboardType: TextInputType.number,
controller: _controller,
),
],
),
actions: <Widget>[
TextButton(
onPressed: () {
bool isTrue = checkScannedCount(int.parse(_controller.text));
if (isTrue) {
var model = args.copyWith(ScannedCount: args.Count);
context.read<ProductCubit>().updateProduct(model);
Navigator.pop(context);
Navigator.pop(context);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Lütfen sayımı tekrarlayınız."),
),
);
Navigator.pop(context);
controller.resumeCamera(); //Its not starting camera again.
}
},
child: const Text('Tamam')),
],
),
);
});
} else {
showDialog(
context: context,
builder: (context) {
return WillPopScope(
onWillPop: () async {
Navigator.pop(context);
controller.resumeCamera();
return true;
},
child: AlertDialog(
title: const Text('Hatalı Barkod veya Ürün'),
content: const Text('Yanlış ürünü veya barkodu okutuyor olabilirsiniz. Kontrol edip tekrar ediniz.'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
controller.resumeCamera();
},
child: const Text('Tamam')),
],
),
);
});
}
});
}
qr_code_scanner no longer supported . Since the underlying frameworks of this package, zxing for android and MTBBarcodescanner for iOS are both not longer maintaned . use mobile_scanner
I have a list of images, and a function that picks an image from that list randomly:
AssetImage imagePicker() {
Random randomNumberGen = Random();
int index = randomNumberGen.nextInt(bgImgList.length);
return AssetImage(bgImgList[index]);
}
And I want a button that when clicking it will call this function and refresh the screen.
floatingActionButton: FloatingActionButton(
onPressed: () { imagePicker(); },
child: const Text(
'change picture' ,
textAlign: TextAlign.center,
),
The issue is the function is called, but the widget i have is not refreshing so the picture doesn't change
this is the widget code:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Israel Geography'),
centerTitle: true,
backgroundColor: Colors.blue[900],
),
body: Center(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imagePicker(),
fit: BoxFit.cover
),
),
)
),
floatingActionButton: FloatingActionButton(
onPressed: () { imagePicker(); },
child: const Text(
'change picture' ,
textAlign: TextAlign.center,
),
),
);
}
Technically, you are calling the imagePicker() method twice, and there is also no state that is holding the final picked image.
Also, this makes the screen not static anymore. The displayed image is changing on each button click, so there is dynamic information in your UI now, so you need to convert your Stateless widget into a Stateful one so you can do setState() whenever the visible information changes.
So after converting to Stateful,
your State class should have a variable like
AssetImage pickedImage = AssetImage(...); // a default image
And in your imagePicker() method, you can assign the pickedImage var with the chosen image instead of returning it.
AssetImage imagePicker() {
Random randomNumberGen = Random();
int index = randomNumberGen.nextInt(bgImgList.length);
// this will rebuild your UI
setState(() {
pickedImage = AssetImage(bgImgList[index]);
});
}
And in your widget, instead of this:
image: imagePicker(),
Do this:
image: pickedImage,
And every time on button click, you pick a new image, rebuild the UI because of setState and now pickedImage will be pointing to another image.
You need the state for a random image. StatefulWidget is one way to accomplish that.
class ImagePicker {
static Image random() {
return Image.network('https://picsum.photos/500/300?andom=${DateTime.now().millisecondsSinceEpoch}');
}
}
class ImagePickerWidget extends StatefulWidget {
const ImagePickerWidget();
#override
State<ImagePickerWidget> createState() => _ImagePickerWidgetState();
}
class _ImagePickerWidgetState extends State<ImagePickerWidget> {
Image _random = ImagePicker.random();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: _random),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _random = ImagePicker.random()),
child: const Icon(Icons.refresh),
),
);
}
}
If you want to keep a widget stateless, provider is one way to that. See Simple app state management for details.
How can I display Image A on the user's screen if it is false or Image B if it is true, Image A is the first one that appears, when the user clicks on it, the state changes to true and switches to Image B, and switches once the user clicks on it, the state changes to true or false.
Image A = false
Image B = true
Image A - Image B
class _MyAppState extends State<MyApp> {
bool closedImage = false;
bool openImage = true;
bool switchOn = false;
void _onSwitchChanged(bool value) {
setState(() {
switchOn = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(scaffoldBackgroundColor: Colors.white),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
),
body:
Center(
child: InkWell(
onTap: () {
Switch(
onChanged: _onSwitchChanged,
value: switchOn,
);
},
child: Container(
color: Colors.white,
child: ClipRRect(
child: switchOn ? Image.asset('lib/assets/closed.png') : Image.asset('lib/assets/open.png')
)
),
),
)
),
);
}
}
Just toggle the switchOn variable like this:
void _onSwitchChanged(bool value) {
setState(() {
switchOn = !switchOn;
});
}
I think your method _onSwitchChanged needs to use the incoming bool value argument (which is supplied by the Switch).
Here's a similar example showing typical usage:
import 'package:flutter/material.dart';
class SwitchFieldPage extends StatefulWidget {
#override
_SwitchFieldPageState createState() => _SwitchFieldPageState();
}
class _SwitchFieldPageState extends State<SwitchFieldPage> {
bool switchVal = false;
String monkey = 'A';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Switch Field'),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Monkey $monkey'),
Switch(
onChanged: (val) { // ← remember to use val (bool)
print('Switch value: $val');
setState(() {
switchVal = val; // this sets the Switch setting on/off
monkey = val ? 'B' : 'A'; // change your monkey source
});
},
value: switchVal,
)
],
),
),
),
);
}
}
You can use a GestureDetector or InkWell to detect when the user presses on the image. For updating the image, I'd suggest learning state management. To make this simple for now, we're going to use StreamBuilder.
screen.dart:
final ScreenBloc _screenBloc = ScreenBloc();
// This is inside your widget build
StreamBuilder<AuthState>(
stream: _screenBloc.pic,
initialData: false,
builder: (context, snapshot) {
return GestureDetector(
onTap: ()=> _screenBloc.toggle(),
child: snapshot.data?Image.asset('lib/assets/closed.png') : Image.asset('lib/assets/open.png'),
);
},
)
screen_bloc.dart:
class ScreenBloc{
bool _currentState=false;
StreamController<bool> _picStream = StreamController<bool>();
Stream<bool> get pic => _picStream.stream;
void toggle(){
_currentState=!_currentState;
_picStream.add(_currentState);
}
}
I have created one method outside the scaffold in the build method but not able to setState() from there.
I have written code like this :
#override
Widget build(BuildContext context) {
//Method that returns alert dialog
method(){
setState(() {
selectedType = newValue;
enableBrand = true;
});
}
//Main scaffold from where i'm calling the alert dialog method
return scaffold()
}
But this doesn't work, the state is not getting updated, so can anyone suggest what is the issue here?
I want to show an AlertDialog on click of a button so i have created a method for that in the build method and trying to setState() from there but it is not working.
Thanks in advance.
void _showDialog() {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder( // StatefulBuilder
builder: (context, setState) {
return AlertDialog(
actions: <Widget>[
],
);
},
);
},
);
}
First of all, is your class extending StatefulWidget?
In the onPressed of your button you could do something like this example.
An AlertDialog can give back a value when popped. I just took the example Alertdialog for now and returned a String.
Then you can set your state with the new value.
onPressed: () async {
var newValue = await showDialog(
context: context,
builder: (c) => AlertDialog(
title: Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('This is a demo alert dialog.'),
Text(
'Would you like to approve of this message?'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Approve'),
onPressed: () {
Navigator.of(context).pop("YOUR_NEW_VALUE");
},
),
],
));
//newValue now has the value "YOUR_NEW_VALUE"
setState((){
selectedType = newValue;
enableBrand = true;
});
}
I have a FLUTTER problem that I couldn't solve.
Scenario:
1. Implement a QR reader application.
2. The app, read the QR code
3. When you read the QR code, you redirect me to a user's detail page
Problem:
I want to edit that person's data, that's why place a TexFormField, valid fields, but when I call
FUTURE function to send the parameters by post, transforming the body in a JSON so that my server detects it, the button DOES NOTHING.
This is My code
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child : Text("Escanea el codigo QR ", style: TextStyle(fontSize: 25.0),)
),
),
floatingActionButton: FloatingActionButton(
onPressed: obtenerValorQR,
child: Icon(Icons.settings_overscan,),
backgroundColor:Color(0xFF56AB2F)
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
---------------------------LOGIC -------------------------
Future obtenerValorQR()
async{
_scantemp= await FlutterBarcodeScanner.scanBarcode("#004297", "salir", true);
setState(() {
value=_scantemp;
});
if (value == null) {
Navigator.pushNamed(context, QrPageRoute);
} else {
Navigator.pushNamed(context, HomePageRoute, arguments: value);
}
}
2. App read QR code
Widget _infoPerfilUsuario(BuildContext context , index ){
return Container(
height: 120.0,
child: Card(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: ListTile(
leading: CircleAvatar(backgroundImage:
NetworkImage(widget.usuarios[index].urlFoto), radius: 30.0,),
title: Text("Nombre: ${widget.usuarios[index].nombres}"),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Apellidos: ${widget.usuarios[index].apellidos}"),
Text("Zona: ${widget.usuarios[index].territorio}")
],
),
),
)
),
);
}
QR DETAIL
4. I WANT TO OTHER PARAMETERS IN DETAILPAGE FOR EXAMPLE " PESO" BUT TH RAISED BUTTON DONT COMPILE THE CODE
Code where I send the "peso" parameter that I implement, but does not do what I am looking for.
widget _botonesAcciones(BuildContext context , int index ){
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
RaisedButton(child: Text("SAVE "), color: Colors.green,
onPressed: () {
final form = formKey.currentState;
if(form.validate()) {
_sendData( context , index );
Navigator.pushNamed(context, QrPageRoute);
}
}
),
],
);
}
I IMPLEMENT THIS FUNCTION IF THE FIELD IS VALIDATED, I just want the data to be sent, I don't want the response body returned, just send the data to my DataBase
Future <void> _sendData (BuildContext context , int index ) async {
final url = Uri.https( _url,'/searchdata.php');
await http.post(url,
body: json.encode({
"id" : "${widget.usuarios[index].idUsuarioMobile}",
"peso" : peso
}),
);
}
Something is wrong?
I think my mistake is in the sendData () function
Hi the solucion is simple:
void _sendData(BuildContext context , int index ) {
var url = Uri.https( _url,'/updatePuntos.php');
http.post(url,
body: json.encode({
"id" : "${widget.usuarios[index].idUsuarioMobile}",
"peso" : peso
}),
);
Looking for me econtre, the answer to my question, was something as simple as returning a void method and sending the data to the server. You should use,
body: json.encode
it will make your life easier.