比较两个列表时出现 Flutter RangeError

Flutter RangeError while when comparing two list

你好,我有 2 个列表,我想在 ListViewBuilder 中使用它们。

名单:

List times = ['08:30', '09:00', '09:30', '10:00', '13:00'];
List obj = [true,false,true];

我试过这个:

ListView.builder(
                controller: scrollController,
                shrinkWrap: true,
                itemCount: times.length,
                itemBuilder: (BuildContext context, int index) {
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: InkWell(
                      onTap: () {
                        setState(() {
                          selected = index;
                          debugPrint(tarih[index]);
                        });
                      },
                      child: Container(
                        color: obj[index] ? Colors.yellow : Colors.red,
                        height: 30,
                        width: 12,
                        child: Text(times[index]),
                      ),
                    ),
                  );
                },
              ),

这里是错误:

我知道这个错误的原因。因为 obj.lengthtimes.length

不匹配

但我还是想创建另一个 Containers。 我该如何解决?

这里有很多方法可以避免这种情况min(int,int) 方法使用最低整数查找

obj[min(index,obj.length-1)] ? Colors.yellow : Colors.red,

widget 可能喜欢这个

      ListView.builder(
        // controller: scrollController,
        shrinkWrap: true,
        itemCount: times.length,
        itemBuilder: (BuildContext context, int index) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: InkWell(
              onTap: () {
                setState(() {
                  selected = index;
                  // debugPrint(tarih[index]);
                });
              },
              child: Container(
                color: obj[min(index,obj.length-1)] ? Colors.yellow : Colors.red,
                height: 30,
                width: 12,
                child: Text(times[index]),
              ),
            ),
          );
        },
      )

你努力实现dartpad live

class _MyAppState extends State<MyApp> {
  int selected = 0;

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

  List times = ['08:30', '09:00', '09:30', '10:00', '13:00'];
  List obj = [];

  @override
  Widget build(BuildContext context) {
    var column = Column(
      children: [
        Container(
          height: 200,
          child: Row(
            children: [
              Expanded(
                child: Image.network(
                  "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Salto_del_Angel-Canaima-Venezuela08.JPG/1200px-Salto_del_Angel-Canaima-Venezuela08.JPG",
                  // fit: BoxFit.cover,
                  fit: BoxFit.fitWidth,
                ),
              ),
            ],
          ),
        )
      ],
    );
    obj = List.generate(times.length, (index) => false);
    var children2 = [
      ListView.builder(
        // controller: scrollController,
        shrinkWrap: true,
        itemCount: times.length,
        itemBuilder: (BuildContext context, int index) {
          if (selected == index)
            obj[index] = true;
          else
            obj[index] = false;
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: InkWell(
              onTap: selected != index
                  ? () {
                      setState(() {
                        selected = index;
                        print(selected);
                        // debugPrint(tarih[index]);
                      });
                    }
                  : null,
              child: Container(
                color: obj[index]
                    ? Colors.yellow
                    : Colors.red,
                height: 30,
                width: 12,
                child: Text(times[index]),
              ),
            ),
          );
        },
      ),
      DropdownButton(
          items: [
            DropdownMenuItem(
              child: Text("1"),
              value: "1",
              onTap: () {},
            )
          ],
          onChanged: (values) {
            // _dropdown1=values;
          })
    ];
    return MaterialApp(
      // theme: theme(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: children2,
          )),
    );
  }
}

好吧,可能还有其他方法可以做到这一点,我所做的就是按顺序复制 obj 列表项目,因为 times 列表中有项目。如果数字不相等,最后加上剩余的数字。

 List times = [
'08:30',
'09:00',
'09:30',
'10:00',
'13:00',
'13:00',
'13:00',
'13:00',
'13:00',
];

List obj = [true, false, true];

@override
Widget build(BuildContext context) {
// Remaining length of times list after we copy
int remaining = times.length % obj.length;
//Exact Number of times to copy obj
int exactNumber = (times.length - remaining) ~/ obj.length;
List shallowList = [];
// Using for loop copy the list as many as exactNumber
for (int i = 0; i < exactNumber; i++) {
  shallowList += obj;
}
// Add add remaining subList 
// Then we have obj list with same length as times
List finalShallowList = [...shallowList, ...obj.sublist(0, remaining)];
// Create Separate Index for obj that we can reset
return Scaffold(
  body: Container(
    child: ListView.builder(
      shrinkWrap: true,
      itemCount: times.length,
      itemBuilder: (BuildContext context, int index) {
        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: InkWell(
            onTap: () {},
            child: Container(
               // Loop over finalShallowList instead of obj
              color: finalShallowList[index] ? Colors.yellow : Colors.red,
              height: 30,
              width: 12,
              child: Text(times[index]),
            ),
          ),
        );
      },
    ),
  ),
);