且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flutter-如何将变量从一个飞镖类传递到另一个飞镖类

更新时间:2023-11-23 10:00:22

尝试一下.

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(
      home: new MainPage(),
    ));

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => new _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int count = 0;
  bool isMultiSelectStarted = false;

  void onMultiSelectStarted(int count, bool isMultiSelect) {
    print('Count: $count  isMultiSelectStarted: $isMultiSelect');
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        backgroundColor: Colors.blue,
        title: new Text('Home'),
      ),
      body: new Center(
        child: new RaisedButton(
          child: new Text('Go to SecondPage'),
          onPressed: () {
            Navigator.of(context).push(
              new MaterialPageRoute(
                builder: (context) {
                  return new SecondPage(onMultiSelectStarted);
                },
              ),
            );
          },
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  int count = 1;
  bool isMultiSelectStarted = true;

  final Function multiSelect;

  SecondPage(this.multiSelect);

  @override
  _SecondPageState createState() => new _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new RaisedButton(
        child: new Text('Pass data to MainPage'),
        onPressed: () {
          widget.multiSelect(widget.count, widget.isMultiSelectStarted);
        },
      ),
    );
  }
}