dart Flutter using Filter in ListView.builder got RangedError

omqzjyyz  于 2023-04-03  发布在  Flutter
关注(0)|答案(1)|浏览(103)

我是新的Flutter我想要一个过滤器的基础上的标签,包含在后类和我使用DropDownButton2包时,我改变了DropDownButton的值,它确实更新_currentposts它看起来很好,直到我向下滚动和范围错误显示了,但当我跳转到其他页面,然后跳回列表视图是好的
下面是我的代码在家里. dart

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:info_bank/post/post.dart';
import 'package:info_bank/screens/search.dart';
import 'package:info_bank/sidemenu/side_menu.dart';
import 'package:google_fonts/google_fonts.dart';

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

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

List<Post> _currentposts = allPost;

class _HomeState extends State<Home> {
  //var post = <SizedBox>[];

  int cnt = 0;

  @override
  Widget build(BuildContext context) {
    double baseWidth = MediaQuery.of(context).size.width;
    double baseHeight = MediaQuery.of(context).size.height;
    String dropdownValue = 'All';
    double FilterWidth = 88; // width 76 88 100 136
    return Scaffold(
        appBar: AppBar(
          titleSpacing: 0.0,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              IconButton(
                icon: const Icon(
                  Icons.list,
                  color: Colors.black,
                ),
                onPressed: () => Scaffold.of(context).openDrawer(),
              ),
              Stack(
                children: <Widget>[
                  Expanded(
                    child: ConstrainedBox(
                      constraints: BoxConstraints(
                          maxWidth: FilterWidth), // max text length
                      child: HomeFilter(),
                    ),
                  ),
                ],
              ),
              Expanded(
                child: Center(
                  child: Text(
                    'InfoBank',
                    textAlign: TextAlign.center,
                    style: GoogleFonts.courgette(),
                  ),
                ),
              ),
            
            ],
          ),
          automaticallyImplyLeading: false,
          centerTitle: true,
          
          actions: <Widget>[
            Row(
              children: <Widget>[
                IconButton(
                    color: Colors.black,
                    icon: const Icon(Icons.search),
                    onPressed: () {
                      Navigator.of(context).push(
                          MaterialPageRoute(builder: (context) => Search()));
                      //Navigator.pushNamed(context, '/search');
                    }),
              ],
            ),
          ],
        ),
        drawer: SideMenu(),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: _currentposts.length,
                  itemBuilder: (context, index) {
                    //final _currentpost = _currentposts[index];
                    return MyPost(
                      child: _currentposts[index].title,
                    );
                  }),
            ),
          ],
        ));
  }
}

List<String> list = <String>['All', 'Followed'];

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

  @override
  State<HomeFilter> createState() => _HomeFilter();
}

class _HomeFilter extends State<HomeFilter> {
  String selectedValue = list.first;
  @override
  Widget build(BuildContext context) {
    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        isExpanded: true,
        items: list
            .map((item) => DropdownMenuItem<String>(
                  value: item,
                  child: Text(
                    item,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ))
            .toList(),
        value: selectedValue,
        onChanged: (value) {
          print(value);
          print(selectedValue);
          if (selectedValue != value) {
            switch (value) {
              case "All":
                filterResults(0);
                //print("All");
                break;
              case "Followed":
                filterResults(1);
                //print("Followed");
                break;
            }
          }
          selectedValue = value as String;
        },
       
        buttonStyleData: ButtonStyleData(
          height: 50,
          width: 180,
          padding: const EdgeInsets.only(left: 14, right: 14),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14),
            border: Border.all(
              color: Colors.black26,
            ),
            color: Color(0xff272727),
          ),
          elevation: 2,
        ),
        iconStyleData: const IconStyleData(
          icon: Icon(
            Icons.arrow_forward_ios_outlined,
          ),
          iconSize: 14,
          iconEnabledColor: Colors.yellow,
          iconDisabledColor: Colors.grey,
        ),
        dropdownStyleData: DropdownStyleData(
            maxHeight: 200,
            width: 200,
            padding: null,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(14),
              color: Color(0xff272727),
            ),
            elevation: 8,
            offset: const Offset(-20, 0),
            scrollbarTheme: ScrollbarThemeData(
              radius: const Radius.circular(40),
              thickness: MaterialStateProperty.all(6),
              thumbVisibility: MaterialStateProperty.all(true),
            )),
        menuItemStyleData: const MenuItemStyleData(
          height: 40,
          padding: EdgeInsets.only(left: 14, right: 14),
        ),
      ),
    );
  }

  void filterResults(int val) {
    int i = 0;
    String filtertag = '';
    if (val == 1) {
      filtertag = 'follow';
    }
    print("filterResults");
    final current = allPost.where((_currentpost) {
      final Posttag = _currentpost.tag;
      return Posttag.contains(filtertag);
    }).toList();
    print(val);
    print(current);
    setState(() => _currentposts = current);
  }
}

和post.dart

import 'package:flutter/material.dart';

class MyPost extends StatelessWidget {
  final String child;

  MyPost({required this.child});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Container(
        height: 400,
        color: Colors.deepPurple[200],
        child: Center(
            child: Text(
          child,
          style: TextStyle(fontSize: 40),
        )),
      ),
    );
  }
}

class Post {
  final String title;
  final String tag;
  const Post({
    required this.title,
    required this.tag,
  });
}

const allPost = [
  Post(title: 'Post 1', tag: 'follow'),
  Post(title: 'Post 2', tag: 'follow'),
  Post(title: 'Post 3', tag: 'follow'),
  Post(title: 'Post 4', tag: 'recommend'),
  Post(title: 'Post 5', tag: 'recommend'),
];

结果应该是,当我改变dropdownbutton值时,listview构建器应该被更新
先谢谢你

vsnjm48y

vsnjm48y1#

您遇到的错误可能是因为在DropDownButton2值更改时,_currentposts列表正在被修改,但ListView.builder没有被重建以反映新的过滤列表。
要修复此问题,可以将_currentposts列表移动到_HomeState类中,并在filterResults方法中更新它,该方法在DropDownButton2值更改时调用。然后,您可以调用setState以使用更新的过滤列表重建ListView.builder。

相关问题