美文网首页
Flutter GlobalKey

Flutter GlobalKey

作者: gaookey | 来源:发表于2020-10-26 15:09 被阅读0次

GlobalKey 可以帮助我们访问某个 Widget 的信息,包括 WidgetStateElement 等对象

可以在 HomePage 中直接访问 HomeContent 中的内容

class HomePage extends StatelessWidget {
  final GlobalKey<_HomeContentState> homeKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("demo"),
      ),
      body: HomeContent(key: homeKey),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.data_usage),
        onPressed: () {
          print("${homeKey.currentState?.value}");
          print("${homeKey.currentState?.widget.name}");
          homeKey.currentState?.stateM();
          homeKey.currentState?.widget.contentM();
        },
      ),
    );
  }
}

class HomeContent extends StatefulWidget {
  final String name = "HomeContent";

  HomeContent({Key? key}) : super(key: key);

  @override
  _HomeContentState createState() => _HomeContentState();

  contentM() {
    print("contentM");
  }
}

class _HomeContentState extends State<HomeContent> {
  final String value = "_HomeContentState";

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  stateM() {
    print("stateM");
  }
}

相关文章

网友评论

      本文标题:Flutter GlobalKey

      本文链接:https://www.haomeiwen.com/subject/wvvpmktx.html