AbdulRahmanAlHamali / flutter_typeahead

A TypeAhead widget for Flutter, where you can show suggestions to users as they type
BSD 2-Clause "Simplified" License
829 stars 348 forks source link

TextField text doesnot update after change #546

Closed kuromadara closed 11 months ago

kuromadara commented 11 months ago

I'm trying to update textfield text after a item is selected but its not working

import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:pragya/models/models.dart';

class CommonDropdown extends StatefulWidget { final List dropdownList; final int? selectedIndex; final ValueSetter<int?>? onChanged;

const CommonDropdown({ super.key, required this.dropdownList, required this.selectedIndex, required this.onChanged, });

@override _CommonDropdownState createState() => _CommonDropdownState(); }

class _CommonDropdownState extends State { final TextEditingController slectedTextController = TextEditingController();

@override Widget build(BuildContext context) { return TypeAheadField( suggestionsCallback: (pattern) async { return widget.dropdownList .where((element) => element.name.toLowerCase().contains(pattern.toLowerCase())) .toList(); },

  builder: (context, slectedTextController, FocusNode focusNode) {
    return TextField(
      controller: slectedTextController,
      focusNode: focusNode,
      // autofocus: true,
      decoration: const InputDecoration(
        labelText: 'Select',
      ),
    );
  },
  itemBuilder: (context, CommonIdName suggestion) {
    return ListTile(
      title: Text(suggestion.name),
    );
  },
  onSelected: (CommonIdName suggestion) {
    final index = widget.dropdownList.indexOf(suggestion);
    widget.onChanged?.call(index + 1);
    setState(() {
      slectedTextController.text = suggestion.name; // Set the text here
    });
    print("after selecting: ${slectedTextController.text}");
  },
  loadingBuilder: (context) => const Text('Loading...'),
  errorBuilder: (context, error) => const Text('Error!'),
  emptyBuilder: (context) => const Text('No items found!'),
);

} }

kuromadara commented 11 months ago

ok found a solution in closed issue

ronsrebro commented 8 months ago

ok found a solution in closed issue

@kuromadara Next time it would be great if you added a link to the issue here, so other won't need to go find it too

I think this is probably what you were referring to https://github.com/AbdulRahmanAlHamali/flutter_typeahead/issues/544

or TDLR

create your own controller, that way you can use it in the onSelected callback