[英]Flutter pass data from one class to another(statefull widget)
How can i pass the data that i get from user via _textController and save it on a variable on the other class?我如何传递通过_textController 从用户那里获得的数据并将其保存在另一个 class 上的变量中? I want to get the data that i get from the user and save it on a variable on the other class
我想获取从用户那里获取的数据并将其保存在另一个 class 上的变量中
final _textController = TextEditingController();
String userPost = "";
@override
Widget build(BuildContext context) {
final double height = MediaQuery.of(context).size.height;
final double width = MediaQuery.of(context).size.width;
return ScreenUtilInit(
designSize: const Size(375, 812),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.amber,
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color.fromRGBO(95, 44, 130, 1),
Color.fromRGBO(73, 160, 157, 1),
])),
Padding(
padding: EdgeInsets.all(60.sp),
child: TextFormField(
controller: _textController,
decoration: InputDecoration(
labelText: 'What s your name?',
suffixIcon: IconButton(
onPressed: () {
_textController.clear();
},
icon: const Icon(Icons.clear))),
),
),
SizedBox(
height: 5.h,
),
MaterialButton(
elevation: 0,
onPressed: () {
setState(() {
userPost = _textController.text;
_textController.clear();
});
},
and displayed here:并显示在这里:
showToast();
NotificationService().showNotification(
1,
'You can, ',
randomName!,
);
},
I don t know how to pass the data我不知道如何传递数据
I think u can use Riverpod StateProvider.我想你可以使用Riverpod StateProvider。
final valueProvider = StateProvider<String>(
(ref) => "",
);
For using this valueProvider
u must use ConsumerStatefulWidget instead of StatefulWidget要使用此
valueProvider
,您必须使用 ConsumerStatefulWidget 而不是 StatefulWidget
Editing valueProvider
编辑
valueProvider
ref.watch(valueProvider.state).state = _textController.text
Using valueProvider
from another ConsumerStatefulWidget使用来自另一个 ConsumerStatefulWidget 的
valueProvider
final text = ref.watch(valueProvider.notifier).state
NOTE笔记
I recommend you look State Management in Flutter topic I think it is critical part of Flutter Development.我建议你看看Flutter 主题中的 State 管理,我认为这是 Flutter 开发的关键部分。
u could simply call the showtoast() function in the onpressed() for any button and pass it the parameters which you want to use,您可以简单地在 onpressed() 中为任何按钮调用 showtoast() function 并将其传递给您要使用的参数,
as作为
onpressed()
{
showtoast('message to toast');
other code--
}
and change this并改变这个
showToast();
NotificationService().showNotification(
1,
'You can, ',
randomName!,
);
},
to到
showToast(String message);
NotificationService().showNotification(
1,
'You can, ',
message,
);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.