0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.