我有一个无状态小部件 A 和有状态小部件 B。A 调用 B(B 是 A 的子级之一)。 A 在小部件 D 中有一个函数(D 也是 A 的子级),它需要 C 布尔值进行比较,该值在 B 小部件的函数中设置。如何将 C 从 B 传播到 A?
另外,我希望 C 是可选的,以便每次渲染 A 时它的值都变为 null。
试试这个:
class B extends StatefulWidget {
//define a callback and call it when c is updated
final ValueChanged<bool?> onChanged;
const B({super.key, required this.onChanged});
@override
State<B> createState() => _BState();
}
class _BState extends State<B> {
bool? c;
void updateC(bool value) {
setState(() {
c = value;
});
widget.onChanged(c);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
updateC(true); //update c to true
},
child: const Text('Update C')),
),
);
}
}
//Need to make class A stateful, because we need to show the updated value of "c" on UI.
class A extends StatefulWidget {
const A({super.key});
@override
State<A> createState() => _AState();
}
class _AState extends State<A> {
bool? c;
void handleCChanged(bool? value) {
// c = value; //update the c value not visible on screen
//need to use setState for showing the updated value on screen
setState(() {
c = value;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
B(onChanged: handleCChanged),
D(c: c),
],
),
);
}
}
//A as stateless value of c is updating but not visible on UI
/*
class A extends StatelessWidget {
bool? c; //c will be updated by callback
A({super.key, this.c});
void handleCChanged(bool? value) {
c = value; //update the c value
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
B(onChanged: handleCChanged),
D(c: c),
],
),
);
}
}
*/
class D extends StatelessWidget {
final bool? c;
const D({super.key, this.c});
@override
Widget build(BuildContext context) {
// Using the value of C for comparison or any other logic
return Text('Value of C: ${c.toString()}');
}
}