Flutter 中的 GlobalKey

前沿

flutter 局部刷新 可以用到GlobalKey

GlobalKey是一个特殊的标识符,它用于在Widget树中唯一标识一个Widget,

并允许我们在Widget树之外访问该Widget的状态或属性。它通常用于在多个Widget之间共享状态、访问子Widget的方法或属性,以及执行一些全局操作。

 

注意:

GlobalKey不应该在build方法中初始化,否则会每次build都重建GlobalKey,更好的办法是让State对象拥有GlobalKey对象,

然后在 State.initState 的方法中初始化GlobalKey。

下面用个代码案例来更好的理解
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // 定义 GlobalKey 用于获取按钮的状态
  final GlobalKey<_CounterButtonState> buttonKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter App'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 使用 CounterButton,并传入 GlobalKey
              CounterButton(key: buttonKey),
              SizedBox(height: 20),
              // 在这里显示当前计数
              ElevatedButton(
                onPressed: () {
                  // 当按钮被点击时,调用按钮的 increaseCount 方法
                  buttonKey.currentState?.increaseCount();
                },
                child: Text('Increase Count'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// CounterButton Widget,用于显示当前计数
class CounterButton extends StatefulWidget {
  // 接收 GlobalKey
  const CounterButton({Key? key}) : super(key: key);

  @override
  _CounterButtonState createState() => _CounterButtonState();
}

class _CounterButtonState extends State<CounterButton> {
  int count = 0;

  // 增加计数的方法
  void increaseCount() {
    setState(() {
      count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      'Count: $count',
      style: TextStyle(fontSize: 24),
    );
  }
}

 

我们首先创建了一个GlobalKey,
用于获取CounterButton的状态。然后我们在MyApp中使用CounterButton,并将这个GlobalKey传递给CounterButton。
当按钮被点击时,我们通过GlobalKey获取CounterButton的状态,并调用其方法来更新计数。 
 
它允许我们在Flutter应用中跨Widget获取其他Widget的状态或执行操作。
posted @ 2024-05-07 18:16  -鹿-  阅读(19)  评论(0编辑  收藏  举报