I am implementing a ListView, where each widget in the children contains two buttons. These buttons are meant to add a new widget above or below the current one, as shown in the diagram below. enter image description here The issue I am facing is that when I click either button, the added widget is not positioned correctly, and the title is also incorrect, as shown in below. enter image description here

我想不出该怎么修理它.以下是完整的代码:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 40),
        child: CustomListView(
          controller: ListController(
            items: ['a', 'b', 'c'],
          ),
        ),
      ),
    );
  }
}

class CustomListView extends StatefulWidget {
  const CustomListView({
    super.key,
    required this.controller,
  });

  final ListController controller;

  @override
  State<CustomListView> createState() => _CustomListViewState();
}

class _CustomListViewState extends State<CustomListView> {
  late final ListController controller;

  @override
  void initState() {
    super.initState();
    controller = widget.controller..addListener(() => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      itemCount: controller.items.length,
      itemBuilder: (context, index) => Entry(
        index: index,
        controller: controller,
      ),
    );
  }
}

class Entry extends StatefulWidget {
  const Entry({
    super.key,
    required this.index,
    required this.controller,
  });

  final int index;
  final ListController controller;

  @override
  State<Entry> createState() => _EntryState();
}

class _EntryState extends State<Entry> {
  late final int index;
  late final String title;

  @override
  void initState() {
    super.initState();
    index = widget.index;
    title = widget.controller.items[index];
    print('build row $title');
  }

  @override
  Widget build(BuildContext context) => ListTile(
        title: Text(title),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextButton(
              child: const Text('Add above'),
              onPressed: () => widget.controller.insertAbove(index),
            ),
            TextButton(
              child: const Text('Add below'),
              onPressed: () => widget.controller.insertBelow(index),
            ),
          ],
        ),
      );
}

class ListController extends ChangeNotifier {
  List<String> items;

  ListController({required this.items});

  void insertAbove(int index) {
    items.insert(index, 'above-${items[index]}');
    notifyListeners();
  }

  void insertBelow(int index) {
    items.insert(index + 1, 'below-${items[index]}');
    notifyListeners();
  }
}

推荐答案

问题是您在_EntryState中定义了indextitle,并在initState中对它们进行了初始化.这些条目不会对列表更改做出react ,还可能使用错误的索引从列表中获取元素.将它们移动到build方法,以便在每次重新生成时更新它们:

class _EntryState extends State<Entry> {
  // Remove the late variables here

  @override
  Widget build(BuildContext context) {
    final index = widget.index;
    final title = widget.controller.items[index];

Flutter相关问答推荐

创建多个具有适当填充和对齐的按钮的最佳方法

从外部类动态更改IconButton的图标

修复后期变量的抖动皮棉

如何删除使用isscllable时出现的左边距?

如何管理枚举类型的阻塞事件?

任务';:app:check DebugDuplicateClasss';的Ffltter Share_plus抛出执行失败

如果我使用搜索栏,如何在嵌套滚动视图中停止自动滚动?

在Dart中使用Riverpod代码生成时出现问题(addListener)

我如何在Android 13中通过Flutter应用程序打开文件(不是图像、视频或音频)?

没有固定宽度的小部件可以约束文本小部件吗?

Flutter 中的区域不匹配

有没有办法在没有收缩包装的情况下在列中使用 ListView.Builder?

转换函数上传文件上传Uint8List

Flutter - 根据从第一个 DropdownButtonForm 中 Select 的内容在第二个 DropdownButton 上显示选项

Future.wait() 中的 futures 可以顺序调用吗?

Flutter Widget 测试:无法使用 find.byWidget() 找到小部件

使用 mocktail 包进行单元测试时,类型Null不是Future类型的子类型

Flutter NavigationBar 忽略我的背景 colored颜色

我已经删除了我的 .android 密钥库,但我没有使用它,如何生成一个新的?

使用 hydrad_bloc 的预览包