flutter

Global key

coens 2022. 5. 15. 14:39

https://api.flutter.dev/flutter/widgets/GlobalKey-class.html

 

GlobalKey class - widgets library - Dart API

A key that is unique across the entire app. Global keys uniquely identify elements. Global keys provide access to other objects that are associated with those elements, such as BuildContext. For StatefulWidgets, global keys also provide access to State. Wi

api.flutter.dev

특정 stateful위젯의 state위젯에 접근하게 해준다.

 

최소 예제

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyKey(),
    );
  }
}

class MyKey extends StatelessWidget {
  final counterKey = GlobalKey<_CounterState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Counter(
          key: counterKey,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          counterKey.currentState!.increment();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class Counter extends StatefulWidget {
  const Counter({Key? key}) : super(key: key);

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return Text('$count');
  }

  void increment() {
    setState(() {
      count++;
    });
  }
}

- 글로벌 키 생성
final counterKey = GlobalKey<_CounterState>();

- 해당키를 stateful위젯의 생성자에 넣음
Counter(key: counterKey,)

- 위젯의 state내부의 메서드를 사용
counterKey.currentState!.increment();