【问题标题】:How to select only one item in ListView and render it?如何在 ListView 中只选择一项并呈现它?
【发布时间】:2021-03-11 13:29:37
【问题描述】:

刚开始学习flutter,对LsitViewBuilder有点疑惑。

我有这个 ListView,它通过 rootBundle 在本地访问 JSON 数据,但我希望当我点击某个项目时它只会在第二页上打开它。

我非常想知道如何选择。

我的列表视图

List<dynamic> buy;

  @override
  void initState() {
    super.initState();
    rootBundle.loadString('assets/dados.json').then((jsonData) {
      this.setState(() {
        buy = jsonDecode(jsonData);
      });
    });
  }

........

ListView.builder(
      itemCount: buy?.length ?? 0,
      itemBuilder: (_, index) {
      return buildCardBuy(context, index, buy);
      }
),

【问题讨论】:

  • 请提供您的 buildCardBuy() 函数的代码。

标签: flutter flutter-layout


【解决方案1】:

您可以使用 GestureDetector 小部件包装您的列表视图项目,使 Tap 事件导航到另一个页面并点击该项目。

ListView.builder(
      itemCount: buy?.length ?? 0,
      itemBuilder: (_, index) {
        return GestureDetector(
            child: buildCardBuy(context, index, buy),
            onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                    // the first refeers to the property on your detail DetailScreen
                    // and the second refers to the current buy being render on
                    // this list view builder
                    builder: (context) => DetailScreen(buy: buy),
                ),
            );
        );
      }
),

在你的 DetailScreen 中类似

class DetailScreen extends StatelessWidget {
  final dynamic buy;

  DetailScreen({Key key, @required this.buy}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      ),
      body: Container()
    );
  }
}

【讨论】:

    【解决方案2】:

    我将构建第二个小部件(我们称之为 ItemWidget),它代表您要“打开”的对象的详细信息页面。

    然后,我将向该 ItemWidget 添加一个属性,用于您需要传递的对象数据。

    之后我将实现逻辑,以便在单击列表项时,它会使用新的 ItemWidget 切换当前列表小部件,并将单击对象的属性传递给它。

    【讨论】:

      猜你喜欢
      • 2013-04-07
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多