derkro99
derkro99

Reputation: 51

Adding WidgetSpan to TextField results in 'dimensions != null': is not true'

Ive been trying to add WidgetSpans to a TextField (via the buildTextSpan() in a TextEditingController) and ran into the crash: "Failed assertion: [..] : 'dimensions != null': is not true". While trying to find a solution ive only ran across people with similar issues, but wasnt able to find a solution to this. My Code(and Problem) is similar to the comment posted on the issue https://github.com/flutter/flutter/issues/30688#issuecomment-870034058.

  @override
  TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
    final atIndex = text.indexOf('@');
    var spans = <InlineSpan>[];

    if (atIndex != -1) {
      spans.add(TextSpan(text: text.substring(0, atIndex)));
      spans.add(
        WidgetSpan(
          alignment: PlaceholderAlignment.middle,
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(4.0),
              child: Text('@'),
            ),
          ),
        ),
      );
      spans.add(TextSpan(text: text.substring(1 + atIndex)));
    } else {
      spans.add(TextSpan(text: text));
    }

    return TextSpan(
      children: spans,
    );
  }

Is there any fix/workaround for this failed assertion?

Upvotes: 4

Views: 1860

Answers (2)

Ahn Sejong
Ahn Sejong

Reputation: 11

If you can solve your problem by setting PlaceholderDimensions, try below. The length and order of 'dimensions' must be the same as the number of 'PlaceholderSpan'. There's just one 'WidgetSpan' In your 'buildTextSpan' method. Hence just one 'PlaceholderDimension' included in 'dimensions'

List<PlaceholderDimensions> dimensions = [
  const PlaceholderDimensions(
      size: Size(8+?, 8+?) //size of yout WidgetSpan
      , alignment: PlaceholderAlignment.middle,
  )
];

final textPainter = TextPainter(
    text : buildTextSpan(...),
)..setPlaceholderDimensions(dimensions)




 

Upvotes: 1

derkro99
derkro99

Reputation: 51

It turns out that this feature is not yet in the stable channel. Using the master channel "fixed" this problem enabling the provide code snippet to run without modifications.

For information on changing channels see: https://stackoverflow.com/a/61157330/10832540

Upvotes: 1

Related Questions