如何重建Flutter的根小部件?

时间:2020-10-14 21:07:27

标签: flutter flutter-provider flutter-routes flutter-build

我正在使用提供程序包来检测“ todaysTasks”中的更改,但是如您所见,“ todayTasks”取决于存储DayTasks列表的DaysRecords,所以我想要的是每当我重新构建根小部件(即MyApp)时在DaysRecords.recordsList中推送DayTask,但找不到任何方法。 有什么解决办法吗?

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,

1 个答案:

答案 0 :(得分:0)

您可以使用ChangeNotifierProvider包装MyApp的父窗口小部件(我猜是主要方法上是MaterialApp),而不是包装在MyApp内。

然后使用MyApp的build方法初始化对应的提供程序,或使用使用者重新构建(管理您的状态)。

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,
      ),
    );
  }
}