Home > database >  How to use Flutter Extended Text Field library
How to use Flutter Extended Text Field library

Time:01-03

I would like to use the extended_text_field library using the WidgetSpan. There is an example on how to create an EmailText widget, but I don't understand how to integrate this into the ExtendedTextField. The documentation is not clear to me. Can someone post an example, please?

CodePudding user response:

You can take a look at my other answer.

But in general, if you take a look at the docs, you'll see that there are different classes that you can extend, such as SpecialText, SpecialTextSpanBuilder, and then you decide what you want to build.

This code example is taken from my above-linked answer.

If there's an @ symbol, it will be placed in a Chip widget:

import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        dividerColor: Colors.green,
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          backgroundColor: Colors.blue,
          body: ExtendedTextField(
            cursorColor: Colors.black,
            style: TextStyle(color: Colors.red),
            decoration: InputDecoration(
              border: OutlineInputBorder(),
            ),
            specialTextSpanBuilder: MySpecialTextSpanBuilder(),
          ),
        ),
      ),
    );
  }
}

class MySpecialTextSpanBuilder extends SpecialTextSpanBuilder {
  @override
  TextSpan build(String data,
      {TextStyle? textStyle, SpecialTextGestureTapCallback? onTap}) {
    final lookingFor = "@";
    final splitData = data.split(" ");
    final spans = splitData.map((e) {
      if (e == lookingFor) {
        return WidgetSpan(
          child: Chip(
            label: Text(e),
          ),
        );
      } else {
        return TextSpan(
          text: e,
          style: TextStyle(color: Colors.red),
        );
      }
    }).toList();
    return TextSpan(children: spans, style: textStyle);
  }

  @override
  SpecialText? createSpecialText(String flag,
      {TextStyle? textStyle,
      SpecialTextGestureTapCallback? onTap,
      required int index}) {
    // TODO: implement createSpecialText
    throw UnimplementedError();
  }
}
  • Related