我可以从小部件外部调用 setState 吗?我尝试注册子窗口小部件的 setState - 并从外部调用它。它似乎不起作用 - 这是为什么?
import 'package:flutter/material.dart';
import 'package:linkimager/sizes.dart';
import 'package:linkimager/store.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
ScreenSizes.init(MediaQuery.of(context).size);
int number = 0;
return MaterialApp(
home: Scaffold(
body: ChildWidget(number),
floatingActionButton: FloatingActionButton(
onPressed: () {
number++;
Renderer.setStateChild();
},
child: const Icon(Icons.add),
),
),
);
}
}
class ChildWidget extends StatefulWidget {
final int number;
const ChildWidget(this.number, {super.key});
@override
ChildWidgetState createState() => ChildWidgetState();
}
class ChildWidgetState extends State<ChildWidget> {
@override
void initState() {
print("registered setStateChild");
Renderer.setStateChild = () => setState;
super.initState();
}
@override
Widget build(BuildContext context) {
return Center(child: Text(widget.number.toString()));
}
}
class Renderer {
static Function setStateChild = () {};
}
我不是在寻找状态管理工具,而是想了解是什么阻碍了外部渲染
我为你做了这个例子:
void main() {
Renderer.setStateChild = () => setState;
Renderer.setStateChild()();
}
void setState(){
for (int i = 0; i < 10; i++) {
print('hello ${i + 1}');
}
}
class Renderer {
static Function setStateChild = () {};
}
您的问题可能是 setStateChild 返回一个函数,因此您可能错过了额外的调用“Renderer.setStateChild()();”