Last active
April 10, 2023 16:56
-
-
Save najeira/5579ace0640d12a7ef4d74f932fc66cb to your computer and use it in GitHub Desktop.
GestureRecognizerBuilder that hold and dispose GestureRecognizers for RichText
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
), | |
], | |
), | |
); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello