flutter - When I press the card how to set card data into text field in flutter
问题描述
When I press my card, I want to set my card data into the text field. my Card Widget and it's another stateful widget. And I need to set this card data into my text field
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
shrinkWrap: true,
children: <Widget>[
Form(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: TextFormField(
decoration: InputDecoration(
labelText: "CupCake Name",
controller: cupCake,
onChanged: (cupcake) {
cupcakeName = cupcake;
},
),
),
),
]
LoadData(),
),
);
}
This is my Card Widget and it's another stateful widget. And I need to set this card data into my text field
class LoadData extends StatefulWidget {
const LoadData({Key? key}) : super(key: key);
@override
_LoadDataState createState() => _LoadDataState();
}
class _LoadDataState extends State<LoadData> {
@override
Widget build(BuildContext context) {
return Container(
child: ListView(
return GestureDetector(
onTap: () => {print("Test")},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
child: Container(
padding: EdgeInsets.all(16),
child: Column(
children: <Widget>[
Text(
data['cupcake_name'],
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
data['description'],
style: TextStyle(
fontSize: 20,
),
),
],
);
}).toList(),
),
}
}
解决方案
看看flutter简单的状态管理。基本上,当您拥有与小部件树的子树共享且相关的状态时,您应该封装并提升该状态,使其与需要与其交互的第一个小部件一样高。
1 创建将处理所需状态的模型
class CupCakeState extends ChangeNotifier {
CupCake? cupcake;
void selectCupcake(CupCake newCake){
this.cupCake=newCupcake;
notifyListeners();
}
2 在小部件树中提供模型
ChangeNotifierProvider(
create: (context) => CupCakeState(),
child: const MyApp(),
),
3 现在您可以使用它来阅读上下文。在您的卡中:
class _LoadDataState extends State<LoadData> {
@override
Widget build(BuildContext context) {
return Container(
child: ListView(
return GestureDetector(
onTap: () => {context.read<CupCakeState>().selectCupcake(CupCake(name:data['cupcake_name'],price:data['cupcake_price']))},
...
或者创建一个每次调用 notifylisteners() 时都会重建的小部件
Consumer<CupCakeState>(
builder: (context, cupcpakeState, child) {
cupcake.value=cupcpakeState.price;//assign the price to the controller
return TextFormField(
decoration: InputDecoration(
labelText: "CupCake Name",
controller: cupCake,
onChanged: (cupcake) {
cupcakeName = cupcake;
},
),
},
)
推荐阅读
- xml - Wix boostrapper 设置以防止防火墙阻止应用程序
- email - 我正在尝试发送自动周年纪念列表。我的代码没有返回错误,但没有发送电子邮件
- python - Marshmallow 模式:允许任何额外字段,只要其名称与模式匹配
- angular - 如何在动态加载的角度组件中共享组件
- c++ - 为什么 C++ big endian 到 int16 with bitshift 不起作用?
- typescript - 在字符串值成员中使用枚举
- performance - 如何在 KQL 中使用服务器获取顶级 CPU 的详细信息
- html - 当元素可见和不可见时,CSS Flexbox 在不同的行中显示元素
- json - JSON文件中的超链接值
- javascript - 我想在 MVC UI 的剑道网格中选择展开和折叠行