如何从父类更新子类?- Flutter

yjghlzjz  于 2023-08-07  发布在  Flutter
关注(0)|答案(1)|浏览(123)

我正在制作我的第一个TODO应用程序,在用户写了一个新的笔记后,我正在努力更新我的应用程序。我希望在用户从NewNotePage单击保存和Navigator.pop()后更新HomePage的子类(HomeBody)。
这是我的父类HomePage表单,我想更新子类,子类是HomeBody作为脚手架的主体。

class HomePage extends StatefulWidget {
  const HomePage({super.key});
  static const String routeName = '/home';

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    ...
      // ----------------------Center-------------------------------
      body: const HomeBody(),
      // ----------------------BOTTOM--------------------------------
      bottomNavigationBar: const HomeBottomAppBar(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushNamed(context, NewNotePage.routeName).then((_) {
            setState(() {});
            print("Action after Navigator.pop()");
          });
        },
        child: const Icon(Icons.create),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}

字符串
子类看起来像这样,我想更新这个类,以显示用户所做的新注解。

class HomeBody extends StatefulWidget {
  const HomeBody({super.key});

  @override
  State<HomeBody> createState() => _HomeBodyState();
}

class _HomeBodyState extends State<HomeBody> {
  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(5),
      children: <Widget>[
        if (notesList.isNotEmpty)
          for (var note in notesList)
            NoteWidget(
                note: note,
                onDeletePressed: () {
                  DataDB.delete(note: note, context: context).then((value) {
                    setState(() {});
                  });
                })
        else ...[
          Container(
            alignment:
                AlignmentGeometry.lerp(Alignment.center, Alignment.center, 0),
            child: Text(
              "Add your first note",
              style: Theme.of(context)
                  .textTheme
                  .titleMedium!
                  .copyWith(color: Colors.black.withOpacity(0.5)),
            ),
          ),
        ],
      ],
    );
  }
}


这里是NewNotePage的状态,用户记录并保存它,然后页面弹出到HomePage

@override
  Widget build(BuildContext context) {
    return Scaffold(
      ...
      // ----------------------Center-------------------------------
      body: NewNoteBody(controller: contentController),
      // ----------------------BOTTOM--------------------------------
      bottomNavigationBar: const BottomAppBar(
        notchMargin: 4,
        clipBehavior: Clip.antiAlias,
      ),
      floatingActionButton: FloatingActionButton(
        tooltip: 'save',
        onPressed: () async {
          if (titleController.text.isNotEmpty ||
              contentController.text.isNotEmpty) {
            NoteModel note = NoteModel(
              title: titleController.text,
              content: contentController.text,
            );
            await DataDB.addNote(note: note).then((value) {
              Navigator.pop(context);
            });
          } else {
            Navigator.pop(context);
          }
        },
        child: const Icon(
          Icons.done_rounded,
          size: 32,
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
    );
  }

jchrr9hc

jchrr9hc1#

好吧,我会回答我自己的问题,因为我发现我犯了一个多么愚蠢的错误。将控制器传递给子部件的方法工作得很好,它不工作,因为控制器的初始化是在一个孩子的initState中,我只是忘记了重新启动应用程序。
我在这里找到的问题的解决方案:https://stackoverflow.com/a/60869283/21395456
所以我将展示如何将控制器传递给孩子。

class HomePageController {
  late void Function() updateBodyState;
}

class HomePage extends StatelessWidget {
  HomePage({super.key});
  static const String routeName = '/home';

  final HomePageController myController = HomePageController();

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Scaffold(
      backgroundColor: theme.colorScheme.primaryContainer,
      // ----------------------TOP--------------------------------
      appBar: AppBar(
        title: const Text(
          'Notes',
          style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
        ),
      ),
      // ----------------------Center-------------------------------
      body: HomeBody(controller: myController),
      // ----------------------BOTTOM--------------------------------
      bottomNavigationBar: const HomeBottomAppBar(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushNamed(context, NewNotePage.routeName).then((_) {
            myController.updateBodyState();
            print("setStates");
          });
        },

字符串
下面是子类:

class HomeBody extends StatefulWidget {
  const HomeBody({super.key, required this.controller});
  final HomePageController controller;

  @override
  State<HomeBody> createState() => _HomeBodyState();
}

class _HomeBodyState extends State<HomeBody> {
  @override
  void initState() {
    super.initState();
    widget.controller.updateBodyState = () {
      setState(() {});
    };
  }


我想我大概明白我做了什么,所以如果有什么问题,我可以试着回答。

相关问题