Prompt Title: flutter

Created 1 year ago
Votes 0
Views 238 times
0

Prompt Detail:

If you want to separate the functions for Button A and Button B into different files, you can still use setState() by passing a callback function to the buttons. Here's an example:

First, create a new file called button_a.dart and add the following code:

dart
import 'package:flutter/material.dart'; class ButtonA extends StatelessWidget { final Function() onPressed; ButtonA({required this.onPressed}); @override Widget build(BuildContext context) { return ElevatedButton( onPressed: onPressed, child: Text('Button A'), ); } }

This creates a new ButtonA widget that accepts a callback function as a parameter.

Now, create a new file called button_b.dart and add the following code:

dart
import 'package:flutter/material.dart'; class ButtonB extends StatelessWidget { final Function() onPressed; ButtonB({required this.onPressed}); @override Widget build(BuildContext context) { return ElevatedButton( onPressed: onPressed, child: Text('Button B'), ); } }

This creates a new ButtonB widget that also accepts a callback function as a parameter.

Finally, in your main page, you can use these new widgets like this:

dart
import 'package:flutter/material.dart'; import 'button_a.dart'; import 'button_b.dart'; class MainPage extends StatefulWidget { @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Main Page'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have clicked the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), SizedBox(height: 20), ButtonA( onPressed: _incrementCounter, ), SizedBox(height: 20), ButtonB( onPressed: _incrementCounter, ), ], ), ), ); } }

As you can see, we are passing the _incrementCounter function as a parameter to both ButtonA and ButtonB. When either button is pressed, it will call this function and update the state of the _MainPageState widget.

I hope this helps! Let me know if you have any other questions.

avatar
Vicky
Shared 1 prompt
Created 1 year ago

Leave a Comment