Anonymous
Поставщик не обновляет значение
Сообщение
Anonymous » 05 янв 2025, 00:24
У меня есть провайдер, который устанавливает значение для PIN-кода, но я не могу получить доступ к его значению с другого экрана. Что я делаю неправильно?
Я пробовал много способов решить эту проблему, но не могу заставить ее работать.
Виджет, в котором я устанавливаю значение булавки:
Код: Выделить всё
class PinDemo extends StatelessWidget {
const PinDemo({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => PinValue(),
child: PinputExample(),
);
}
}
class PinputExample extends StatefulWidget {
const PinputExample({Key? key}) : super(key: key);
@override
State
createState() => _PinputExampleState();
}
class _PinputExampleState extends State {
final pinController = TextEditingController();
final focusNode = FocusNode();
final formKey = GlobalKey();
@override
void dispose() {
pinController.dispose();
focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => PinValue(),
child: Consumer(builder: (context, myTheme, child) {
const focusedBorderColor = Color(0xFF9500c8);
const fillColor = Color.fromRGBO(243, 246, 249, 0);
var borderColor = myTheme.primaryColor;
return Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Directionality(
textDirection: TextDirection.ltr,
child: Pinput(
controller: pinController,
focusNode: focusNode,
androidSmsAutofillMethod:
AndroidSmsAutofillMethod.smsUserConsentApi,
listenForMultipleSmsOnAndroid: true,
defaultPinTheme: defaultPinTheme,
validator: (value) {
return value == '222222' ? null : 'Pin is incorrect';
},
onCompleted: (pin) {
debugPrint('onCompleted: $pin');
Provider.of(context, listen: false).setPin(pin);
print(Provider.of(context, listen: false).pin);
//Where i set the value for pin. Here it prints normally
},
onChanged: (value) {
debugPrint('onChanged: $value');
},
cursor: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets.only(bottom: 9),
width: 22,
height: 1,
color: focusedBorderColor,
),
],
),
errorPinTheme: defaultPinTheme.copyBorderWith(
border: Border.all(color: Colors.redAccent),
),
),
),
],
),
);
}));
}
}
Виджет, в котором я пытаюсь получить доступ к значению PIN-кода (но получает пустую строку):
Код: Выделить всё
class TokenValidateScreen extends StatelessWidget {
const TokenValidateScreen({super.key});
@override
Widget build(BuildContext context) {
return Consumer
(builder: (context, pinValue, child) {
return Scaffold(
body: Container(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
height: 40,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const PinputExample(),
const SizedBox(height: 80),
ReusableButton(
text: "Validate",
onPressed: () {
print(pinValue.pin);
//Where i try to print the value and get the empty string
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => TakePhotoScreen(),
),
);
},
),
const SizedBox(
height: 25,
),
Text("Reenviar token", style: CustomTextStyle.h2()),
Text(pinValue.pin, style: CustomTextStyle.h2())
],
),
],
),
),
),
);
});
}
}
Класс PinValue
Код: Выделить всё
import 'package:flutter/material.dart';
class PinValue with ChangeNotifier {
String _pin = '';
String get pin => _pin;
void setPin(String pin) {
_pin = pin;
notifyListeners();
}
}
Согласно примерам, которые я вижу, я не могу найти, что не так, может ли кто-нибудь мне помочь?
Подробнее здесь:
https://stackoverflow.com/questions/755 ... ting-value
1736025844
Anonymous
У меня есть провайдер, который устанавливает значение для PIN-кода, но я не могу получить доступ к его значению с другого экрана. Что я делаю неправильно? Я пробовал много способов решить эту проблему, но не могу заставить ее работать. Виджет, в котором я устанавливаю значение булавки: [code]class PinDemo extends StatelessWidget { const PinDemo({super.key}); @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => PinValue(), child: PinputExample(), ); } } class PinputExample extends StatefulWidget { const PinputExample({Key? key}) : super(key: key); @override State createState() => _PinputExampleState(); } class _PinputExampleState extends State { final pinController = TextEditingController(); final focusNode = FocusNode(); final formKey = GlobalKey(); @override void dispose() { pinController.dispose(); focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => PinValue(), child: Consumer(builder: (context, myTheme, child) { const focusedBorderColor = Color(0xFF9500c8); const fillColor = Color.fromRGBO(243, 246, 249, 0); var borderColor = myTheme.primaryColor; return Form( key: formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Directionality( textDirection: TextDirection.ltr, child: Pinput( controller: pinController, focusNode: focusNode, androidSmsAutofillMethod: AndroidSmsAutofillMethod.smsUserConsentApi, listenForMultipleSmsOnAndroid: true, defaultPinTheme: defaultPinTheme, validator: (value) { return value == '222222' ? null : 'Pin is incorrect'; }, onCompleted: (pin) { debugPrint('onCompleted: $pin'); Provider.of(context, listen: false).setPin(pin); print(Provider.of(context, listen: false).pin); //Where i set the value for pin. Here it prints normally }, onChanged: (value) { debugPrint('onChanged: $value'); }, cursor: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( margin: const EdgeInsets.only(bottom: 9), width: 22, height: 1, color: focusedBorderColor, ), ], ), errorPinTheme: defaultPinTheme.copyBorderWith( border: Border.all(color: Colors.redAccent), ), ), ), ], ), ); })); } } [/code] Виджет, в котором я пытаюсь получить доступ к значению PIN-кода (но получает пустую строку): [code] class TokenValidateScreen extends StatelessWidget { const TokenValidateScreen({super.key}); @override Widget build(BuildContext context) { return Consumer (builder: (context, pinValue, child) { return Scaffold( body: Container( child: Padding( padding: const EdgeInsets.all(24.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox( height: 40, ), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const PinputExample(), const SizedBox(height: 80), ReusableButton( text: "Validate", onPressed: () { print(pinValue.pin); //Where i try to print the value and get the empty string Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => TakePhotoScreen(), ), ); }, ), const SizedBox( height: 25, ), Text("Reenviar token", style: CustomTextStyle.h2()), Text(pinValue.pin, style: CustomTextStyle.h2()) ], ), ], ), ), ), ); }); } } [/code] Класс PinValue [code]import 'package:flutter/material.dart'; class PinValue with ChangeNotifier { String _pin = ''; String get pin => _pin; void setPin(String pin) { _pin = pin; notifyListeners(); } } [/code] Согласно примерам, которые я вижу, я не могу найти, что не так, может ли кто-нибудь мне помочь? Подробнее здесь: [url]https://stackoverflow.com/questions/75512281/provider-not-updating-value[/url]