Sam12
Sam12

Reputation: 1805

The argument type SearchBar can't be assigned to the parameter type Widget in flutter

I'm trying to implement an automatic Search Bar in Flutter.

When compiling I get the error: The argument type 'SearchBar' can't be assigned to the parameter type 'Widget?'.

class Home extends StatelessWidget {
  Future<List<Post>> search(String search) async {
    await Future.delayed(Duration(seconds: 2));
    return List.generate(search.length, (int index) {
      return Post(
        "Title : $search $index",
        "Description :$search $index",
      );
    });
  }
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: SearchBar<Post>(
            onSearch: search,
            onItemFound: (Post post, int index) {
              return ListTile(
                title: Text(post.title),
                subtitle: Text(post.description),
              );
            },
          ),
        ),
      ),
    );
  }
}

Upvotes: 0

Views: 464

Answers (1)

Nisanth Reddy
Nisanth Reddy

Reputation: 6430

From the official Documentation, you need to call the build method to get a widget.

However, it would be better if you create your SearchBar inside your constructor itself, so that a new one doesn't get created every time.

From the official documentation,

class _MyHomePageState extends State<MyHomePage> {
    SearchBar searchBar;

    AppBar buildAppBar(BuildContext context) {
      return new AppBar(
        title: new Text('My Home Page'),
        actions: [searchBar.getSearchAction(context)]
      );
    }  

    _MyHomePageState() {
      searchBar = new SearchBar(
      inBar: false,
      setState: setState,
      onSubmitted: print,
      buildDefaultAppBar: buildAppBar
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: searchBar.build(context)
    );
  }
}

Upvotes: 1

Related Questions