https://api.flutter.dev/flutter/widgets/GlobalKey-class.html
최소 예제
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();
'flutter' 카테고리의 다른 글
quicktype.io 를 통해서 데이터 객체 생성하기 (0) | 2023.09.04 |
---|---|
다른 앱으로부터 공유받기 - flutter_sharing_intent (0) | 2023.09.03 |
Firebase 데이터베이스 Stream데이터 읽기 (0) | 2022.05.19 |
Value Key (0) | 2022.05.15 |