Home > Software engineering >  how to detect @ sign using Flutter Field
how to detect @ sign using Flutter Field

Time:06-10

i have a textfield that require user to call another user using @ sign. So if the user press @ there should be a popup at the top of the textfield.

i have try using this something Like this it should only show when user type @ only....

CodePudding user response:

With the TextField you use it has the onChanged method to catch all the changes made to the text field input and with that you can evaluate the first character of the text field and that's what I'd recommend you to.

With my example, it prints every change made in the input of the textfield. It also checks only the first character of the input and prints to the console. You also can use setState instead of print to for example sets a boolean and then handles the Plugin you use.

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextField(
          controller: _controller,
          onChanged: (String value) {
            value.characters.first == '@'
                ? print(
                    'Contains @',
                  )
                : print(
                    'Does not contain @',
                  );
          },
        ),
      ),
    );
  }
}

CodePudding user response:

In flutter_typeahead package, you can add your logic in the suggestionsCallback.

In the example below, i am only calling the api and showing the data if the text starts with @. Modify as per your requirements.

TypeAheadField(
  textFieldConfiguration: TextFieldConfiguration(
    autofocus: true,
    style: DefaultTextStyle.of(context).style.copyWith(
      fontStyle: FontStyle.italic
    ),
    decoration: InputDecoration(
      border: OutlineInputBorder()
    )
  ),
  suggestionsCallback: (pattern) async {
    if("${pattern}".startsWith("@")){
        return await BackendService.getSuggestions(pattern);
    }else{
        return [];
    }
  },
  itemBuilder: (context, suggestion) {
    return ListTile(
      leading: Icon(Icons.shopping_cart),
      title: Text(suggestion['name']),
      subtitle: Text('\$${suggestion['price']}'),
    );
  },
  onSuggestionSelected: (suggestion) {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => ProductPage(product: suggestion)
    ));
  },
)
  • Related