搜索委托,当我点击搜索按钮时,它会显示带有错误子项的红屏! =空

Posted

技术标签:

【中文标题】搜索委托,当我点击搜索按钮时,它会显示带有错误子项的红屏! =空【英文标题】:Search delegate , When I click on Search button it shows red screen with error child! =null 【发布时间】:2020-12-07 17:49:31 【问题描述】:

我通过搜索委托创建了一个搜索选项,但是当我单击搜索按钮时,它显示红色屏幕并显示此错误“以下断言被抛出构建 _SearchPage(dirty, dependencies: [_LocalizationsScope-[GlobalKey#69e74], _InheritedTheme] , state: _SearchPageState#72bb6): 'package:flutter/src/widgets/basic.dart': 断言失败: 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,
    );
  

【问题讨论】:

【参考方案1】:

您可以在下面复制粘贴运行完整代码 你需要buildSuggestions中的return关键字 你可以return ListView.builder

代码sn-p

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

工作演示

完整代码

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

【讨论】:

以上是关于搜索委托,当我点击搜索按钮时,它会显示带有错误子项的红屏! =空的主要内容,如果未能解决你的问题,请参考以下文章

我必须单击两次搜索按钮才能从api获取数据

如何在jTable中读取和搜索文件?

SearchBar 在单击取消按钮之前不显示结果

显示带有操作的搜索栏(栏项)

添加框阴影错误 - 无法点击我的按钮 - SpriteKit

当我在 DataGridView 中单击搜索数据按钮时,它会在 DataGridView 中添加我想要搜索的内容