我使用提供程序包来检测"todaysTasks"中的更改,但正如您所看到的,"todayTasks"取决于存储DayTasks列表的DaysRecords,所以每当我在DaysRecords.recordsList中推送DayTask时,我想要重建我的根小部件(即MyApp(,但无法找到任何方法。有什么解决办法吗??
class MyApp extends StatelessWidget {
static const routeName = '/root';
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
DayTasks todaysTasks = DaysRecords.recordsList.last;
return ChangeNotifierProvider(
create: (context) => todaysTasks,
您可以用ChangeNotificationProvider包装MyApp的父窗口小部件(我猜它是主方法上的MaterialApp(,而不是包装在MyApp内。
然后在MyApp的构建方法中初始化相应的提供程序,或者使用使用者进行重建(管理您的状态(。
void main() {
runApp(MaterialApp(
home: RootWidget(),
));
}
class RootWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => SomeProvider(),
child: MyApp(),
);
}
}
class MyApp extends StatelessWidget {
static const routeName = '/root';
@override
Widget build(BuildContext context) {
final provider = Provider.of<SomeProvider>(context, listen: true);
// DayTasks todaysTasks = provider.recordsList.last;
return Scaffold(
body: AppBar(
automaticallyImplyLeading: false,
),
);
}
}