Reputation: 990
In the following set-up, how would I allow fileb.dart
to access the function reset
that is in filea.dart
:
filea.dart
:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test',
theme: ThemeData(
primaryColor: Colors.pink[200],
),
home: MyHomePage(title: ''),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
MyHomePageState createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage>
{
int testCount = 0;
void test() {
setState(() {
testCount++;
});
}
fileb.dart
import 'package:flutter/material.dart';
import './filea.dart';
class Buttons extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 11.0, top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
FloatingActionButton(
heroTag: "btn1",
onPressed: () => MyHomePageState.test(),
child: const Icon(Icons.cancel),
splashColor: Colors.pink[900],
backgroundColor: Colors.pink[200],
),
),
],
),
),
],
);
}
}
What do I need to change to make this work?
Upvotes: 0
Views: 81
Reputation: 1271
You can achieve this through function callback.
Pass the test callback to ButtonWifget's constructor
and use the callback in fab button onPressed as below mentioned sample code:
// In Button class
Buttons({this.testCallback});
final Function testCallback;
...
FloatingActionButton(
heroTag: "btn1",
onPressed: testCallback,
)
// In MyHomePage class, pass the callback wherever you have used `Buttons` widget
Buttons(testCallback:test());
Hope this helps you :)
Upvotes: 0
Reputation: 1067
You cannot call a function in another class unless it is static
, and it should not deal with any variables that are non-static
/local
or it will through an error.
Another way to call a function is to pass it as an argument to the page.
Upvotes: 1