Search delegate , When I click on Search button it shows red screen with error child! =null

2,521

You can copy paste run full code below
You need return keyword in buildSuggestions
You can return ListView.builder

code snippet

@override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    final suggestionList = query.isEmpty
        ? recentlist
        : statelist.where((element) => element.startsWith(query)).toList();
    return ListView.builder(

working demo

enter image description here

full code

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title), actions: <Widget>[
        IconButton(
          icon: Icon(Icons.search),
          onPressed: () {
            showSearch(context: context, delegate: DataSearch());
          },
        ),
      ]),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class DataSearch extends SearchDelegate<String> {
  final statelist = [
    'Andaman and Nicobar Islands',
    '   Andhra Pradesh',
    'Arunachal Pradesh',
    'Assam',
    'Bihar',
    'Chandigarh ',
    'Chhattisgarh',
    'Dadra and Nagar Havel',
    'Daman and Diu',
    'Delhi',
    'Goa',
    'Gujrat',
    'Haryana',
    'Himachal Pradesh',
    'Uttar Pradesh',
    'Uttarakhand',
    'West Bengal',
    'Sikkim',
    'Meghalya',
    'Mizoram',
  ];
  final recentlist = ['Modingar', 'Ghaziabad', 'Merrut', 'Hapur', 'Delhi'];

  @override
  List<Widget> buildActions(BuildContext context) {
    // action for app bar
    return [
      IconButton(
        onPressed: () {
          query = "";
        },
        icon: Icon(Icons.clear),
      )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    // leading icon on the left of the app bar
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return Container(
      height: 150.0,
      child: Card(
        color: Colors.red,
        shape: StadiumBorder(),
        child: Text(query),
      ),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    final suggestionList = query.isEmpty
        ? recentlist
        : statelist.where((element) => element.startsWith(query)).toList();
    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
          onTap: () {
            showResults(context);
          },
          title: RichText(
            text: TextSpan(
                text: suggestionList[index].substring(0, query.length),
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
                children: [
                  TextSpan(
                      text: suggestionList[index].substring(query.length),
                      style: TextStyle(color: Colors.grey))
                ]),
          )),
      itemCount: suggestionList.length,
    );
  }
}
Share:
2,521
gopal
Author by

gopal

Updated on December 23, 2022

Comments

  • gopal
    gopal over 1 year

    I create a search option by search delegate but When I click on search button it shows the red screen with this error "The following assertion was thrown building _SearchPage(dirty, dependencies: [_LocalizationsScope-[GlobalKey#69e74], _InheritedTheme], state: _SearchPageState#72bb6): 'package:flutter/src/widgets/basic.dart': Failed assertion: line 6938 pos 15: 'child != null': is not true.

    import 'package:flutter/material.dart';
    import 'package:grk_001/screen/main_screen.dart';
    import 'widgets/entry_item.dart';
    
    import 'package:font_awesome_flutter/font_awesome_flutter.dart';
    
    import 'package:grk_001/screen/favourite_screen.dart';
    import 'package:grk_001/Provider/Auth.dart';
    
    import 'package:provider/provider.dart';
    import 'package:grk_001/Provider/cart.dart';
    import 'package:grk_001/widgets/badge.dart';
    import 'package:grk_001/screen/cart_screen.dart';
    import 'package:grk_001/widgets/drawer.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:grk_001/models/main_screen_categories_entry.dart';
    
    class HomeScreen extends StatefulWidget {
      static const String routename = 'homescreen';
    
      @override
      _HomeScreenState createState() => _HomeScreenState();
    }
    
    class _HomeScreenState extends State<HomeScreen> {
      final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
      FirebaseUser Loggedinuser;
      @override
      void didChangeDependencies() {
        // TODO: implement didChangeDependencies
        Future.delayed(Duration.zero).then((_) async {
          await Provider.of<Auth>(context, listen: false).getcurrentuser();
        });
        super.didChangeDependencies();
      }
    
      @override
      Widget build(BuildContext context) {
        final devicesize = MediaQuery.of(context).size;
        return SafeArea(
          child: Scaffold(
            key: _scaffoldkey,
            appBar: AppBar(
              leading: IconButton(
                onPressed: () {
                  _scaffoldkey.currentState.openDrawer();
                },
                icon: Icon(
                  Icons.list,
                  color: Colors.white,
                  size: 35.0,
                ),
              ),
              bottom: PreferredSize(
                preferredSize: const Size.fromHeight(50.0),
                child: Container(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: <Widget>[
                      const SizedBox(
                        width: 10.0,
                      ),
                      Expanded(
                        child: GestureDetector(
                          onTap: () {
                            _scaffoldkey.currentState.openEndDrawer();
                          },
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            alignment: Alignment.center,
                            height: 40.0,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(5.0),
                            ),
                            child: Text(
                              'Categories',
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              title: Text('HomeScreen'),
              actions: <Widget>[
                IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () {
                    showSearch(context: context, delegate: DataSearch());
                  },
                ),
                IconButton(
                  icon: Icon(
                    FontAwesomeIcons.heart,
                    size: 30.0,
                  ),
                  tooltip: 'My Wish List',
                  onPressed: () {
                    Navigator.pushNamed(context, FavouriteScreen.routename);
                  },
                ),
                IconButton(
                  icon: Icon(
                    Icons.notifications,
                    size: 30.0,
                  ),
                  tooltip: 'My Notifications',
                  onPressed: () {},
                ),
                Consumer<Cart>(
                  builder: (_, cartdata, ch) => Badge(
                    child: ch,
                    value: cartdata.itemcount.toString(),
                  ),
                  child: IconButton(
                    onPressed: () {
                      Navigator.pushNamed(context, CartScreen.routename);
                    },
                    icon: Icon(
                      Icons.shopping_cart,
                      size: 40.0,
                    ),
                  ),
                ),
              ],
            ),
            body: MainScreen(),
    //        body: CategoryScreen(),
            endDrawer: Drawer(
              child: Column(
                children: <Widget>[
                  Container(
                    color: Color(0XFFFF4081),
                    height: devicesize.height * 0.10,
                    child: DrawerHeader(
                        margin: EdgeInsets.zero,
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Icon(
                                Icons.apps,
                                color: Colors.white,
                              ),
                              SizedBox(
                                width: 10.0,
                              ),
                              Text(
                                'Categories',
                                style:
                                    TextStyle(color: Colors.white, fontSize: 20.0),
                              ),
                            ],
                          ),
                        )
    //                  child: Text('Categories'),
                        ),
                  ),
                  Container(
                    height: devicesize.height * 0.85,
                    child: ListView.builder(
                      itemBuilder: (context, index) => EntryItem(data[index]),
                      itemCount: data.length,
                    ),
                  )
                ],
              ),
            ),
            drawer: Container(
              width: devicesize.width * 0.65,
              child: DrawerItem(devicesize, context),
            ),
          ),
        );
      }
    }
    
    class DataSearch extends SearchDelegate<String> {
      final statelist = [
        'Andaman and Nicobar Islands',
        '   Andhra Pradesh',
        'Arunachal Pradesh',
        'Assam',
        'Bihar',
        'Chandigarh ',
        'Chhattisgarh',
        'Dadra and Nagar Havel',
        'Daman and Diu',
        'Delhi',
        'Goa',
        'Gujrat',
        'Haryana',
        'Himachal Pradesh',
        'Uttar Pradesh',
        'Uttarakhand',
        'West Bengal',
        'Sikkim',
        'Meghalya',
        'Mizoram',
      ];
      final recentlist = ['Modingar', 'Ghaziabad', 'Merrut', 'Hapur', 'Delhi'];
    
      @override
      List<Widget> buildActions(BuildContext context) {
        // action for app bar
        return [
          IconButton(
            onPressed: () {
              query = "";
            },
            icon: Icon(Icons.clear),
          )
        ];
      }
    
      @override
      Widget buildLeading(BuildContext context) {
        // leading icon on the left of the app bar
        return IconButton(
          icon: AnimatedIcon(
            icon: AnimatedIcons.menu_arrow,
            progress: transitionAnimation,
          ),
          onPressed: () {
            close(context, null);
          },
        );
      }
    
      @override
      Widget buildResults(BuildContext context) {
        // TODO: implement buildResults
        return Container(
          height: 150.0,
          child: Card(
            color: Colors.red,
            shape: StadiumBorder(),
            child: Text(query),
          ),
        );
      }
    
      @override
      Widget buildSuggestions(BuildContext context) {
        // TODO: implement buildSuggestions
        final suggestionList = query.isEmpty
            ? recentlist
            : statelist.where((element) => element.startsWith(query)).toList();
        ListView.builder(
          itemBuilder: (context, index) => ListTile(
              onTap: () {
                showResults(context);
              },
              title: RichText(
                text: TextSpan(
                    text: suggestionList[index].substring(0, query.length),
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                    children: [
                      TextSpan(
                          text: suggestionList[index].substring(query.length),
                          style: TextStyle(color: Colors.grey))
                    ]),
              )),
          itemCount: suggestionList.length,
        );
      }
    }