简体   繁体   中英

How to send onPressed value to another widget Flutter

I want to send data from widget to another widget, in my example I want to send onPressed value as a variable.

appBar: CancelAppBar(onPressed: ),

What should I write after onPressed (in the above code) to send the value: Navigator.of(context).push(MaterialPageRoute(builder: (context) => UnderBuild()));

to a widget in a seperate dart file?

Following is the other file:

class CancelAppBar extends StatefulWidget implements PreferredSizeWidget {
  CancelAppBar({Key? key, required this.onPressed}) : super(key: key);

  final ValueGetter<String> onPressed;
  static final _appBar = AppBar();
  @override
  Size get preferredSize => _appBar.preferredSize;

  @override
  _CancelAppBarState createState() => _CancelAppBarState();
}

class _CancelAppBarState extends State<CancelAppBar> {
  get onPressed => null;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      titleSpacing: 0.0,
      title: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(padding: EdgeInsets.only(left: 8.w)),
          IconButton(
            onPressed: ,
            icon: Icon(Icons.close),
          )
        ],
      ),
      backgroundColor: AppColors.dark,
    );
  }
}

You can access any StatefulWidget variable in the State class with widget getter, like:

class CancelAppBar extends StatefulWidget implements PreferredSizeWidget {
  CancelAppBar({Key? key, required this.onPressed}) : super(key: key);

  final ValueGetter<String> onPressed;
  static final _appBar = AppBar();
  @override
  Size get preferredSize => _appBar.preferredSize;

  @override
  _CancelAppBarState createState() => _CancelAppBarState();
}

class _CancelAppBarState extends State<CancelAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      titleSpacing: 0.0,
      title: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(padding: EdgeInsets.only(left: 8.w)),
          IconButton(
            onPressed: widget.onPressed, /// widget.yourVariable
            icon: Icon(Icons.close),
          )
        ],
      ),
      backgroundColor: AppColors.dark,
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM