【发布时间】:2021-10-13 03:44:18
【问题描述】:
问题:
当我遇到这个问题时,我正在寻找包含在按下的小部件中的单词的中间位置。
我收到错误,多个小部件使用相同的 GlobalKey,同时使用下面的最小可行代码。
我无法解决这个问题。我正在注入 GlobalKeys,它应该是独一无二的,我会希望它们彼此不同。代码确实有效,但我找不到解决方案有点令人沮丧。
我尝试过的:
我已经尝试了之前在 StackOverflow 上发布的问题的几个解决方案,但无济于事,包括使用具有唯一标识符的 Globalkeys 的不同变体以及使用静态 Globalkeys 变量创建一个类:
How to Fix a 'Multiple Widgets used the same Globalkey resource 1
How to Fix a 'Multiple Widgets used the same Globalkey resource 2
How to Fix a 'Multiple Widgets used the same Globalkey resource 3
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatelessWidget {
final scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: SafeArea(
child: Row(
mainAxisSize: MainAxisSize.max,
children: [LeftSideWidget()],
),
),
);
}
}
class DisplayCircle extends StatelessWidget {
final Color color;
DisplayCircle({Key? key, required this.color}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: 120,
height: 120,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
shape: BoxShape.circle,
),
child: CircleAvatar(
backgroundColor: color,
),
);
}
}
class LeftSideWidget extends StatefulWidget {
const LeftSideWidget({
Key? key,
}) : super(key: key);
@override
_LeftSideWidgetState createState() => _LeftSideWidgetState();
}
class _LeftSideWidgetState extends State<LeftSideWidget> {
double thumbWidth = 70.0;
var position = 0.0;
changePosition(GlobalKey key) {
final RenderObject? object = key.currentContext!.findRenderObject();
final RenderBox renderBox = object as RenderBox;
final size = object.semanticBounds;
position = renderBox.localToGlobal(Offset.zero).dy;
setState(() {
position = (size.center.dy + position - (thumbWidth / 2));
print(position.toString());
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.max,
children: [
Spacer(),
WordsToPress(
title: 'TEST LINE 1',
key: GlobalKey(),
onPressed: (GlobalKey key) => changePosition(key),
),
Spacer(),
WordsToPress(
title: 'TEST LINE 2',
key: GlobalKey(),
onPressed: (GlobalKey key) => changePosition(key),
),
Spacer(),
WordsToPress(
title: 'TEST LINE 3',
key: GlobalKey(),
onPressed: (GlobalKey key) => changePosition(key),
),
Spacer(),
],
);
}
}
class WordsToPress extends StatelessWidget {
final String title;
final GlobalKey key;
final Function(GlobalKey) onPressed;
const WordsToPress(
{required this.title, required this.key, required this.onPressed})
: super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapUp: (_) => onPressed(key),
child: Container(
key: key,
child: RotatedBox(
quarterTurns: -1,
child: Text(
title,
),
),
),
);
}
}
问题: 如何正确使用 Globalkeys 以确保每个小部件只有一个?任何帮助将不胜感激。
【问题讨论】: