Skip to content

Instantly share code, notes, and snippets.

@najeira
Last active April 10, 2023 16:56
Show Gist options
  • Save najeira/5579ace0640d12a7ef4d74f932fc66cb to your computer and use it in GitHub Desktop.
Save najeira/5579ace0640d12a7ef4d74f932fc66cb to your computer and use it in GitHub Desktop.
GestureRecognizerBuilder that hold and dispose GestureRecognizers for RichText
// MIT @najeira
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
typedef GestureRecognizerWidgetBuilder = Widget Function(
BuildContext, Map<String, TapGestureRecognizer>);
class GestureRecognizerBuilder extends StatefulWidget {
const GestureRecognizerBuilder({
Key? key,
required this.builder,
}) : super(key: key);
final GestureRecognizerWidgetBuilder builder;
@override
_GestureRecognizerBuilderState createState() =>
_GestureRecognizerBuilderState();
}
class _GestureRecognizerBuilderState extends State<GestureRecognizerBuilder> {
final _recognizers = <String, TapGestureRecognizer>{};
@override
void dispose() {
for (final recognizer in _recognizers.values) {
recognizer.dispose();
}
_recognizers.clear();
super.dispose();
}
@override
Widget build(BuildContext context) {
return widget.builder(context, _recognizers);
}
}
class _MyText extends StatelessWidget {
const _MyText({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureRecognizerBuilder(
builder: (context, recognizers) {
final foo = recognizers.putIfAbsent(
"foo",
() => TapGestureRecognizer(),
)..onTap = () {
// なにか
};
final bar = recognizers.putIfAbsent(
"bar",
() => TapGestureRecognizer(),
)..onTap = () {
// なにか
};
return RichText(
text: TextSpan(
children: [
TextSpan(
text: "link 1",
recognizer: foo,
),
TextSpan(
text: "link 2",
recognizer: bar,
),
],
),
);
},
);
}
}
Copy link

ghost commented Apr 10, 2023

hello

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment