如何按值将变量传递给 Flutter MaterialPageRoute?

时间:2021-01-08 04:59:09

标签: flutter dart

我有一个循环索引,它创建了大约 20 个 ListTiles,可以点击引用其索引的第二个屏幕。但是看起来它是通过引用传递的,因为第二个屏幕上的值始终相同

用户定义的upper_bound ... for(int i=0; i

{ ... 容器 -> ListTile ->

    title: GestureDetector(
      onTap: () async {
          var returnData = await Navigator.push(
              context,
              MaterialPageRoute(builder: (context) =>
                  SecondScreen(
                      index: i,
                  ))
          );}

} 在这种情况下,第二个屏幕总是接收索引作为 upper_bound 而不是我期望的值,即循环时的值。如何传递索引的当前值?

1 个答案:

答案 0 :(得分:1)

在第一页/屏幕

@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("ListTile Example"),
      ),
      body: new ListView(
        children: new List.generate(20, (int index) {
          return new ListTile(
            onTap: () {
              Navigator.of(context).push(
                PageRouteBuilder(
                  opaque: false,
                  pageBuilder: (BuildContext context, _, __) => NextPage(
                    number: index,
                  ),
                ),
              );
            },
            title: new Text(
              "Index No #$index",
              style: new TextStyle(fontWeight: FontWeight.w500, fontSize: 25.0),
            ),
            subtitle: new Text("My subtitle is"),
          );
        }),
      ),
    );
  }

在下一页或第二页

import 'package:flutter/material.dart';

class NextPage extends StatefulWidget {
  final int number;

  NextPage({
    Key key,
    @required this.number,
  }) : super(key: key);
  @override
  _NextPageState createState() => _NextPageState();
}

class _NextPageState extends State<NextPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(widget.number.toString()),
      ),
    );
  }
}