dart TabBarView中的搜索和筛选不起作用

sd2nnvve  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(116)

我无法在TabBarView中搜索和过滤,我尝试过这样做

import 'dart:async';
import 'dart:developer';
import 'package:aliseo_app/models/web_scrapping.dart';
import 'package:aliseo_app/variables/global_variables.dart';
import 'package:flutter/material.dart';
import '../widgets/image_container.dart';

dynamic article;
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  static const routeName = '/home';

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  TextEditingController searchController = TextEditingController();
  int selectIndex = 0;
  String searchQuery = '';

  void updateSearchQuery(String query) {
    final suggestion = article.where((art){
      final articlesTitle = art.title.toLowerCase();
      final input = query.toLowerCase();

      return articlesTitle.contains(input);
    }).toList();

    setState(() => article = suggestion);
  }

  Future newsControl() async {
    await getData();
    setState(() {});
  }

  @override
  void initState() {
    newsControl();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    List<String> tabs = ['Esteri', 'Politica', 'Economia', 'Cultura'];

    return DefaultTabController(
        initialIndex: 0,
        length: tabs.length,
        child: Scaffold(
          backgroundColor: const Color(0xffEEE2DE),
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            leading: IconButton(
                onPressed: () {},
                icon: const Icon(
                  Icons.menu,
                  color: Colors.white,
                )),
          ),
          extendBodyBehindAppBar: true,
          //bottomNavigationBar: const BottomNavBar(
          //  index: 0,
          //),
          body: ListView(
            padding: EdgeInsets.zero,
            children: [
              const _TitleScreen(),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: SizedBox(
                  height: MediaQuery.of(context).size.height * 0.06,
                  child: TextFormField(
                    onChanged: updateSearchQuery,
                    controller: searchController,
                    decoration: InputDecoration(
                        enabled: true,
                        hintText: 'Cerca',
                        fillColor: const Color(0xffEA906C),
                        filled: true,
                        prefixIcon: const Icon(
                          Icons.search,
                          color: Colors.black,
                        ),
                        suffixIcon: const RotatedBox(
                          quarterTurns: 1,
                          //child: Icon(
                          //  Icons.tune,
                          //  color: Colors.grey,
                          //)
                        ),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(20),
                            borderSide: BorderSide.none)),
                  ),
                ),
              ),
              Column(
                children: [
                  TabBar(
                      tabAlignment: TabAlignment.start,
                      labelPadding: const EdgeInsets.only(right: 10),
                      dividerColor: Colors.transparent,
                      indicatorSize: TabBarIndicatorSize.label,
                      isScrollable: true,
                      indicatorColor: const Color(0xff000f24),
                      tabs: tabs
                          .map((tab) => SizedBox(
                        width: 110,
                        child: Tab(
                          icon: Text(
                            tab,
                            style: Theme.of(context)
                                .textTheme
                                .headlineSmall!
                                .copyWith(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ))
                          .toList()),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.60,
                    child: TabBarView(
                        children: tabs
                            .map(
                              (tab) => ListView.builder(
                              padding: EdgeInsets.zero,
                              shrinkWrap: true,
                              itemCount: articles[tab]!.length,
                              itemBuilder: ((context, index) {
                                final article = articles[tab]![index];
                                return Row(
                                  children: [
                                    ImageContainer(
                                      width: MediaQuery.of(context).size.width*0.40,
                                      height: 100,
                                      imageUrl: article.imageUrl,
                                      margin: const EdgeInsets.all(10.0),
                                      borderRadius: 5,

                                    ),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            article.title,
                                            maxLines: null,
                                            overflow: TextOverflow.clip,
                                            style: Theme.of(context)
                                                .textTheme
                                                .titleSmall!
                                                .copyWith(
                                                fontWeight:
                                                FontWeight.bold),
                                          ),
                                          Text(
                                            article.createdAt,
                                            maxLines: 2,
                                            overflow: TextOverflow.clip,
                                            style: Theme.of(context)
                                                .textTheme
                                                .bodySmall!,
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                );
                              })),
                        )
                            .toList()),
                  ),
                ],
              ),
            ],
          ),
        ));

  }

}

class _TitleScreen extends StatelessWidget {
  const _TitleScreen({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(20),
              bottomRight: Radius.circular(20)),
          color: Color(0xff000f24)),
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: ImageContainer(
          height: MediaQuery.of(context).size.height * 0.19,
          width: MediaQuery.of(context).size.width,
          padding: const EdgeInsets.all(20.0),
          imageUrl:
              'https://aliseoeditoriale.it/wp-content/uploads/2022/06/logo-aliseo-footer.png',
        ),
      ),
    );
  }
}

字符串
当我在搜索框中搜索时,屏幕以正确的方式重新加载,但我仍然看到所有的文章,就像什么都没有发生一样,我尝试在线搜索,但我找不到一种方法使其工作。

Map<String, List<Article>> articles = {
'Esteri': foreignArticles,
'Politica': politicsArticles,
'Economia': economicsArticles,
'Cultura': cultureArticles,};


你们能帮我弄明白吗?

htrmnn0y

htrmnn0y1#

你可以这样实现:

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  Map<String, List<Article>> articles = {
    'Esteri': foreignArticles,
    'Politica': politicsArticles,
    'Economia': economicsArticles,
    'Cultura': cultureArticles,
  };
  String query = '';

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: articles.length,
      child: Scaffold(
        body: Column(
          children: [
            TextField(
              onChanged: (value) {
                setState(() {
                  query = value;
                });
              },
            ),
            Expanded(
              child: TabBarView(
                children: [
                  for (final entry in articles.entries)
                    TabContents(
                      list: entry.value,
                      query: query,
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class TabContents extends StatelessWidget {
  const TabContents({
    super.key,
    required this.list,
    required this.query,
  });

  final List<Article> list;
  final String query;

  @override
  Widget build(BuildContext context) {
    List<Article> filteredList;

    if (query.isEmpty) {
      filteredList = [...list];
    } else {
      filteredList = [
        for (final e in list)
          if (e.title.toLowerCase().contains(query.toLowerCase())) e,
      ];
    }

    return ListView.builder(
      itemCount: filteredList.length,
      itemBuilder: (context, index) {
        return Text(
          filteredList[index].title,
        );
      },
    );
  }
}

字符串

相关问题