【问题标题】:Reorderable ListView with future builder in Flutter在 Flutter 中使用未来构建器可重新排序的 ListView
【发布时间】:2021-05-13 02:06:08
【问题描述】:

我正在尝试将 Reorderable ListView 实现为FutureBuilder,但目前我遇到了一个错误并且不知道这意味着什么。我未来的 Widget 'WidgetLook' 已经分配了一个键。

这是我的 Future Builder 代码:

child: FutureBuilder(
  future: getClassList(),
  builder: (BuildContext context, AsyncSnapshot<List> snapchot) {
    if (snapchot.hasData) {
      return ReorderableListView(
        onReorder: _onReorder,
        children: getList(snapchot.data),
      );
    } else
      return CircularProgressIndicator();
  }
)

“getClassList”函数如下所示:

Future<List> getClassList() async {
  final response = await http.get('http://.../classtitle');
  final decoded = json.decode(response.body) as Map<String, dynamic>;
  List classtitlesList = decoded['ClassTitles'];
  return classtitlesList;
}

“getList”函数如下所示:

List<Widget> getList(text) {
  list = [];
  for (int i = 0; i < text.length; i++) {
    list.add(WidgetLook(title: text[i], number: i));
  }
  return list;
}

Widget 本身如下所示:

class WidgetLook extends StatelessWidget {
  final String title;
  final number;
  WidgetLook({this.title, this.number});
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      key: ValueKey(title),
      onTap: () async {...
      },
      child: Container(...
        child: Align(...
        ),
      ),
    );
  }
}

错误信息是这样的:

All children of this widget must have a key.
'package:flutter/src/material/reorderable_list.dart':
Failed assertion: line 75 pos 10: 'children.every((Widget w) => w.key != null)'

The relevant error-causing widget was
FutureBuilder<List<dynamic>>

为什么会出现此错误,因为我已经为我的小部件分配了一个键?

【问题讨论】:

    标签: flutter dart flutter-listview flutter-futurebuilder


    【解决方案1】:

    您需要为小部件列表中的项目添加一个键。 所以你应该在你的小部件中添加密钥:

    class WidgetLook extends StatelessWidget {
      final String title;
      final number;
    
      const WidgetLook({Key key, this.title, this.number}) : super(key: key);
      
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          key: ValueKey(title),
          onTap: () async {
          },
          child: Container(
          child: Align(
          ),
        ),
        );
      }
    }
    

    现在您应该将键值添加到列表中的小部件:

    List<Widget> getList(text) {
      list = [];
      for (int i = 0; i < text.length; i++) {
        list.add(WidgetLook(key: ValueKey(i), title: text[i], number: i));
      }
      return list;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2019-12-15
      • 1970-01-01
      • 2021-11-22
      • 2019-05-23
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      相关资源
      最近更新 更多