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

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

最佳答案

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

例如,

// 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

https://stackoverflow.com/questions/50702749/

相关文章:

dart - 如何在 flutter 中做悠悠球动画?

flutter - 如何在 flutter 中加载所有 dart DateFormat 语言环境?

flutter - 如何在 Flutter 中添加虚线

dart - 如何使用 Flutter 检测用户在我的屏幕上点击的位置?

flutter - 没有为类 'signInWithGoogle' 定义方法 'FirebaseAu

json - 将 JSON 映射到类对象

visual-studio-code - 如何在 Visual Studio Code 中使用 Fl

dart - 如何在 Flutter 中创建带有圆角的自定义模糊形状

flutter - 在 TextFormField 上捕获点击事件

dart - Flutter中的弯曲形状背景标题