Flutter:如何获取父小部件变量?

标签 flutter inheritance

我使用下面的示例来测试和学习如何从子小部件调用父函数。
当您单击 TestButton 时, countRefresh函数被调用,变量 count增加 1。
现在,每次单击按钮时都会更改颜色(蓝色或红色)。

问题 :说我希望颜色根据 count 周围的一些逻辑而改变变量,我如何访问 count来自 TestButton 内的变量小部件?
例如。如果 count是三的倍数,则按钮应为红色,否则为蓝色。

我读过 InheritedWidgets,但似乎变量在 InheritedWidgets 中必须是 final 的(如果我没有在 int count = 0; 之前放置 final,我会收到“此类被标记为不可变”消息错误)。
但基于这个例子,我需要 count每次单击按钮时更改。
InheritedWidgets 的替代品是什么?

import 'package:flutter/material.dart';

class Test extends StatefulWidget {
  static const String id = 'test';
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  int count = 0;
  Color color = Colors.red;

  void refreshCount() {
    setState(() {
      count += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:
            Text('The button was pressed $count time${count == 1 ? '' : 's'}'),
      ),
      floatingActionButton: TestButton(
        color: color,
        notifyParent: refreshCount,
      ),
    );
  }
}

class TestButton extends StatefulWidget {
  TestButton({
    @required this.color,
    @required this.notifyParent,
  });
  final Color color;
  final void Function() notifyParent;
  @override
  _TestButtonState createState() => _TestButtonState();
}

class _TestButtonState extends State<TestButton> {
  Color color;
  void initState() {
    color = widget.color;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        widget.notifyParent();
        setState(() {
          color = color == Colors.red ? Colors.blue : Colors.red;
        });
      },
      child: Container(
        child: Icon(
          Icons.add,
          size: 80,
        ),
        color: color,
      ),
    );
  }
}

最佳答案

I want the color to change based on some logic around the count variable, how can I access the count variable from within the TestButton widget? E.g. if count is a multiple of three then the button should be red, otherwise blue.



您需要通过count到 child 身上,让 child 根据那个值(value)来建立自己。

不要尝试访问父小部件。在声明式编程中,您只能更新状态和重建树。

这是一个关于 Flutter 状态管理的好视频:https://www.youtube.com/watch?v=HrBiNHEqSYU

关于Flutter:如何获取父小部件变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60502447/

相关文章:

Flutter Custom Painter 和键盘问题

初始化基表时 Flutter sqfline 错误

Flutter 列和行

javascript - 我在 JavaScript 中对这个原型(prototype)做错了,有什么想法吗?

class - 图中的 Doxygen 类/函数名称

C# - 继承、覆盖

Python继承基类变量

flutter - 如何从没有上下文的类访问提供者字段?

android - 如何防止抖动中的 Image.file() 滞后?

javascript - 如何让继承在 JavaScript 中起作用?