I have issue's when i will using Function callback

Viewed 64

i have custom button widget from different file, then i create callback function it might will showing pointer from main function, when i'm running i have issues this: Issues

and this code, main layout:

import 'package:flutter/material.dart';
import './increment.dart';

void main() => runApp(MaterialApp(
      home: HomePage(),
    ));

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _counter = 0;
  void increment() {
    setState(() {
      _counter = _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            Text('Result = ${_counter}'),
            SizedBox(
              height: 100,
            ),
            Inc(increment)
            // ElevatedButton(onPressed: increment, child: Text('-'))
          ],
        ),
      ),
    );
  }
}

and this widget custom:

import 'package:flutter/material.dart';

class Inc extends StatelessWidget {
  final Function selectInc;
  Inc(this.selectInc);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 100,
      child: ElevatedButton(onPressed: selectInc(), child: Text('+')),
    );
  }
}

how i can solve this?

1 Answers
onPressed: selectInc()

This is calling the function and using the result. You need to use the function only as a parameter:

onPressed: () => selectInc()

Since your selectInc method is a void function, the exact type the callback requires, you could also omit the anonymous function wrapper and pass your callback directly:

onPressed: selectInc

However, it seems you need some more type safety for the compiler to not complain. Make

final Function selectInc;

look like this:

final VoidCallback selectInc;
Related