Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

dart - How do I pass a variable by value to Flutter MaterialPageRoute?

I have a loop index that is creating ~20 ListTiles that tap to a second screen that reference its index. However it looks like it's passing by reference since the value is always the same on the second screen

user defined upper_bound ... for(int i=0; i<upper_bound;i++)

{ ... Container -> ListTile ->

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

} In this situation, the second screen always receives index as upper_bound and not the value I'd expect which is the value at the time of the loop. How can I pass the current value of the index?

question from:https://stackoverflow.com/questions/65623683/how-do-i-pass-a-variable-by-value-to-flutter-materialpageroute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

in the first page/screen

@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"),
          );
        }),
      ),
    );
  }

in the next or second page

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()),
      ),
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...