Cerca delegato, quando clicco sul pulsante Cerca viene visualizzata una schermata rossa con errore figlio! = null

Aug 18 2020

Creo un'opzione di ricerca dal delegato di ricerca ma quando faccio clic sul pulsante di ricerca viene visualizzata la schermata rossa con questo errore "La seguente asserzione è stata generata durante la creazione di _SearchPage (sporco, dipendenze: [_LocalizationsScope- [GlobalKey # 69e74], _InheritedTheme], dichiara: _SearchPageState # 72bb6): 'package: flutter / src / widgets / basic.dart': asserzione non riuscita: riga 6938 pos 15: 'child! = Null': non è vera.

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,
    );
  }
}

Risposte

1 chunhunghan Aug 19 2020 at 14:42

Puoi copiare e incollare eseguire il codice completo di seguito
Hai bisogno di una returnparola chiave in buildSuggestions
Puoireturn ListView.builder

snippet di codice

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

demo funzionante

codice completo

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,
    );
  }
}