gpt4 book ai didi

flutter - 如何在 InheritedWidget 中调用 setState 或更新值?

转载 作者:行者123 更新时间:2023-12-03 03:23:50 25 4
gpt4 key购买 nike

可重现代码:

void main() => runApp(MaterialApp(home: CountInheritedWidget(child: HomePage())));

class CountInheritedWidget extends InheritedWidget {
CountInheritedWidget({Widget child}) : super(child: child);

final Map<String, int> _map = {"count": 0};

// getter
int get value => _map["count"];

// setter
set value(int x) => _map["count"] = x; // is there anything like setState here?

@override
bool updateShouldNotify(CountInheritedWidget oldCounter) => true;

static CountInheritedWidget of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<CountInheritedWidget>();
}

class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextWidget(),
ButtonWidget(),
],
),
),
);
}
}

class TextWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
int count = CountInheritedWidget.of(context)?.value ?? -1;
return Text("Count = $count");
}
}

class ButtonWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text("Increment"),
onPressed: () {
CountInheritedWidget counter = CountInheritedWidget.of(context);
int count = counter?.value ?? -1;
counter.value = ++count;
},
);
}
}

我想更新 count 的值来自 ButtonWidget ,我确定它会在 CounterInheritedWidget 中得到更新类,但它没有反射(reflect)在屏幕上。怎么打电话 setState或来自 InheritedWidget 的类似内容?

任何帮助将不胜感激,我是 Flutter 和 Dart 的新手,因此很难解决此类问题。谢谢你,祝你有美好的一天。

注:我不是在寻找像 Provider 这样的插件, ScopedModel , Redux对于这种工作。

最佳答案

InheritedWidgets 不能这样做。它们是完全不可变的,没有触发更新的机制。

如果要发出更新,则必须将 InheritedWidget 与 StatefulWidget 结合起来,通常以这种方式完成:

class MyWidget extends StatefulWidget {
const MyWidget({Key key, this.child}) : super(key: key);
final Widget child;

@override
MyState createState() => MyState();
}

class MyState extends State<MyWidget> {
String name;
int age;

@override
Widget build(BuildContext context) {
return MyInherited(
name: name,
age: age,
child: widget.child,
);
}
}

哪里 MyInheritedWidget是:

class MyInherited extends InheritedWidget {
MyInherited({
Key key,
this.name,
this.age,
Widget child,
}) : super(key: key, child: child);

final String name;
final int age;

@override
bool updateShouldNotify(MyInherited oldWidget) {
return name != oldWidget.name && age != oldWidget.age;
}

@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('age', age));
properties.add(StringProperty('name', name));
}
}

是的。那是冗长的。这就是为什么 provider存在。

关于flutter - 如何在 InheritedWidget 中调用 setState 或更新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60041554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com