skip to Main Content

I am creating a generic widget within which I want to display the SearchField widget each time with a different return value.For example:

SearchField<String>
SearchField<CustomObject>

When every time I want to send the value of this object and display it as a return value (so that I can use it generically),
For example:
SearchField<customObjectType>.
How can I declare the customObjectType in the widget?

2

Answers


  1. Dart supports using generics.

    Here, we use T as the type – as it serves as a placeholder for a type that will be specified later.

    class SearchField<T> extends StatelessWidget {
      final Function(T) onSearch;
    
      const SearchField({
        Key? key,
        required this.onSearch,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return TextField(
          onSubmitted: (String value) {
            onSearch(value as T);
          },
        );
      }
    }
    
    
    Login or Signup to reply.
  2. It’s not clear what you aims to achieve, but here’s a parametrized generic widget:

    class SearchField<T> extends StatelessWidget{
      final T genericObject;
    
      const SearchField({super.key, required this.genericObject});
    
      @override
      Widget build(BuildContext context) {
        // do whatever you want with the genericObject
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search