英文:
Does Using Inherited Widget will rebuild it's Child without using SetState
问题
class InheritedRepo extends InheritedWidget {
InheritedRepo({
Key? key,
required Widget child,
required this.name,
}) : super(key: key, child: child);
final String name;
shouldDoSome() {}
static InheritedRepo of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<InheritedRepo>()!;
@override
bool updateShouldNotify(covariant InheritedRepo oldWidget) {
print("name:$name");
print("oldWidget.name:${oldWidget.name}");
return true;
}
}
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
InheritedRepo(
name: 'some name',
child: const FilePickerScreen(),
),
),
);
},
child: const Text("Filepicker Screen"),
),
我创建了一个继承的小部件,但当我尝试修改name变量的值时,子小部件不会重建,甚至updateShouldNotify也不会被调用,打印语句没有执行。
英文:
class InheritedRepo extends InheritedWidget {
InheritedRepo({
super.key,
required super.child,
required this.name,
});
String name
;
shouldDoSome() {}
static InheritedRepo of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<InheritedRepo>()!;
@override
bool updateShouldNotify(covariant InheritedRepo oldWidget) {
print("name:$name");
print("oldWidget.name:${oldWidget.name}");
return true;
}
}
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
InheritedRepo(
name: 'some name',
child: const FilePickerScreen()),
),
);
},
child: const Text("Filepicker Screen"),
),
i created a inherited widget but when i tried to modify the value of name variable the child is not rebuilding , even the updateShouldNotify is not invoking , the print statement didn't executed
答案1
得分: 0
我不认为InheritedWidget会在其属性更改时自动触发其子小部件的重建,InheritedWidget是一种共享状态给其他后代小部件的方式,它没有重建小部件的功能。另外,updateShouldNotify方法用于确定是否应通知小部件的后代关于更改,但它不会直接触发重建。因此,您需要添加setState来重新绘制小部件并重建UI。这里有一些文档可能会有所帮助:https://api.flutter.dev/flutter/widgets/State/setState.html
英文:
I do not think InheritedWidget will automatically trigger a rebuild of its child widgets when its properties change, the InheritedWidget is a otherway of sharing a state to other descendants widgets, it has not function to rebuild the widget. and also for the updateShouldNotify method is used to determine if the widget's descendants should be notified about the change. but, it doesn't directly trigger a rebuild. So, you need to add setState to redraw the widget and rebuild the UI. hHere some documentation might help : https://api.flutter.dev/flutter/widgets/State/setState.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论