Home > Software engineering >  How to send onPressed value to another widget Flutter
How to send onPressed value to another widget Flutter

Time:10-28

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

CodePudding user response:

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

Also, you can notice that:

Then you can use your variable like that:

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: () {
              /// Access your variable by [widget.onPressed]
              widget.onPressed(); /// Call it inside this function because your variable doesn't match directly the [onPressed] of [IconButton] widget
            },
            icon: Icon(Icons.close),
          )
        ],
      ),
      backgroundColor: AppColors.dark,
    );
  }
}
  • Related