当我点击文章时,搜索栏加载了一款从WordPress API获取文章的新闻Flutter 翼应用程序上的文章,我就遇到了这种问题. 我共享屏幕和代码来理解我的 case .

HomePage enter image description here

图标搜索按钮打开搜索栏的操作主屏幕

actions: <Widget>[
              /// First search icon
              FutureBuilder<List>(
                  future: categoryNews.getNewsArticles(),
                  builder: (context, snapshot) {
                    if (snapshot == null || !snapshot.hasData || snapshot.connectionState != ConnectionState.done) {
                      return const SizedBox();

                        // const Icon(
                        //   Icons.search,
                        //   color: Colors.white,
                        // );
                    }
                    return IconButton(
                      icon: const Icon(
                        Icons.search,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => SearchBar(posts: snapshot.data!,),
                          ),
                        );
                      },
                    );
                  }),
            ],

搜索栏一旦打开,就会显示文章,但当我点击文章时,什么也不会发生

   class SearchBar extends StatefulWidget {
  final List posts;
  const SearchBar({
    Key? key,
    required this.posts,
  }) : super(key: key);
  @override
  _SearchBarState createState() => _SearchBarState();
}

class _SearchBarState extends State<SearchBar> {
  final List _searchedPost = [];
  late List _searchedArticles = [];
  //late final data;


  @override
  Widget build(BuildContext context) {
    //var _searchedPost;
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          style: const TextStyle(color: Colors.white),
          decoration: const InputDecoration(
            hintText: "Cerca Articolo",
            hintStyle:
                TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
            border: InputBorder.none,
          ),
          onChanged: (val) {
            setState(() {
              _searchedArticles = widget.posts.where((element) {
                return element["title"]["rendered"].contains(val);
              }).toList();
            });
          },
        ),
      ),
      body: _searchedArticles.isEmpty
          ? Scaffold(
              backgroundColor: Colors.white,
              body: Padding(
                padding: const EdgeInsets.all(12),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      "assets/images/search-illustration.png",
                      height: 230,
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    const Text(
                      'Nessun articolo trovato!',
                      style: TextStyle(
                        fontSize: 20.0,
                        color: Colors.black,
                        fontFamily: "Raleway",
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    const Text(
                      'Inserisci meglio le lettere o parole chiave dell’articolo che stai cercando e riprova.',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.black54,
                        fontFamily: "Raleway",
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    const SizedBox(
                      height: 30,
                    ),
                    // Back to home btn
                    MaterialButton(
                      height: 50,
                      elevation: 0,
                      color: Colors.blue[900],
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: const [
                          Text(
                            'Torna alla home',
                            style: TextStyle(
                                fontSize: 16.0,
                                color: Colors.white,
                                fontFamily: "Raleway",
                                fontWeight: FontWeight.w600),
                          ),
                        ],
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => HomePage(),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
            )
          : ListView.builder(
              itemCount: _searchedArticles.length,
              itemBuilder: (context, i) {
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Card(
                      margin: const EdgeInsets.all(10),
                      elevation: 5,
                      shadowColor: Colors.black26,
                      color: Colors.white,
                      child: InkWell(
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(10),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              //data["_embedded"]["wp:featuredmedia"][0]["link"],),
                              _searchedArticles[i]["_embedded"]
                                          ["wp:featuredmedia"][0]["link"] ==
                                      null
                                  ? const Text("Nessuna immagine caricata")
                                  : Image.network(
                                      _searchedArticles[i]["_embedded"]
                                          ["wp:featuredmedia"][0]["link"],
                                      width: double.infinity,
                                      height: 220,
                                      fit: BoxFit.cover,
                                    ),
                              // Title article
                              Column(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(
                                        left: 16, top: 16, bottom: 16),
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            _searchedArticles[i]["title"]
                                                ["rendered"] as String,
                                            maxLines: 3,
                                            overflow: TextOverflow.clip,
                                            softWrap: true,
                                            style: const TextStyle(
                                              fontSize: 18,
                                              fontWeight: FontWeight.w600,
                                              fontFamily: "Raleway",
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                        onTap: () {
                          if (_searchedPost[i] != null) {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ArticlePage(
                                  data: _searchedPost[i],
                                ),
                              ),
                            );
                          }
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
    );
  }
}

您可以在图片中看到的错误是在ONTAP数据上:_earch edPost[i], 我如何解决此问题?

推荐答案

从您的代码可以看出,On Tap方法调用的是_searchedPost[i],而ListView Builder中使用的列表是_searchedArticles,因此错误是为空列表提供索引

Flutter相关问答推荐

在Flutter 动中绘制ECG图

如何在Ffltter 3.16中设置标准的提升按钮主题?

摆动更改标记可轻敲文本按钮样式

如何将WebViewWidget和WillPopScope结合起来

使用现有Map方法对子类克隆方法的逻辑进行Dart标准化

ScaffoldMessenger 在等待键下方不起作用

Flutter - Riverpod 2.0 - 如何访问 onDispose 回调?

如何拥有 StreamProvider 的多个侦听器,其中稍后添加的侦听器接收最新数据?

没有为类型 'Widget' 定义运算符 '[]' .try 定义运算符[]

Dart 撕掉 const 构造函数

flutter 中 // 和 /// 有什么区别

如何从 showModalBottomSheet 中的 topRight 和 topLeft 移除平边

如何将 void 函数放入单独的 dart 文件的单独页面中

如何在手势检测器中获得涟漪效应

Flutter 中父容器顶部的 Gridview 间距额外区域

使用 Firebase/Flutter 进行应用判断 - 100% 无效请求

如何将图像网络装箱到具有边界半径的容器中

在 Flutter Bloc 中具有称为 status 的属性的一种状态或不同的状态,哪个更可取?

在 Flutter 中更新对象实例属性的最佳实践是什么?该实例嵌套在提供程序类的映射中,如下所示

如何在Flutter 的 initState 中初始化 Firestore 查询