颤动 - 我想将变量从一个类传递到另一个类

时间:2018-06-05 14:35:33

标签: flutter

我只想将int和boolean从一个类传递给另一个类。对于该特定整数可以显示在第二页的应用栏中,需要根据布尔值(True / false)更改背景颜色。

1 个答案:

答案 0 :(得分:8)

在导航器中,您可以将要发送的数据或对象传递给其他类。

例如,

// Data need to sent second screen
class Person {
  final String name;
  final String age;

  Person(this.name, this.age);
}

// Navigate to second screen with data
Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondScreenWithData(person: new Person("Priyank","28"))));

SecondScreenWithData课程中,您可以获得如下传递的数据。

class SecondScreenWithData extends StatelessWidget {
  // Declare a field that holds the Person data
  final Person person;

  // In the constructor, require a Person
  SecondScreenWithData({Key key, @required this.person}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen With Data"),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            // Display passed data from first screen
            new Text("Person Data  \nname: ${person.name} \nage: ${person.age}"),
            new RaisedButton(
              child: new Text("Go Back!"),
              onPressed: () {
                // Navigate back to first screen when tapped!
                Navigator.pop(context);
              }
            ),
          ],
        )
      ),
    );
  }

检查完整Navigation Demo