Home > Enterprise >  is there anyway i could pass an async funtion as a parameter to a constructor
is there anyway i could pass an async funtion as a parameter to a constructor

Time:10-09

i am trying to assign an async function to an instance variable i have tried

class TextBox extends StatefulWidget {
  late String message;
  late bool isPass;
  late Function(String?) callback;

  TextBox(String message, bool isPass, Future<dynamic> Function(String?) async func) {
    this.message = message;
    this.isPass = isPass;
    this.callback = func;
  }
}

i but get the following exception: Expected to find ')' i know why i get the error i just dont know the proper syntax to do this in dart

CodePudding user response:

You can use this line of code:

  final Future<void> callback;

You can change the void type to any data type you want.

CodePudding user response:

You do not need to use the keyword async because making the function return a Future is enough. Also, you can write a constructor without a body.

class TextBox extends StatefulWidget {
  final String message;
  final bool isPass;
  final Future<dynamic> Function(String?) callback;

  TextBox(this.message, this.isPass, this.callback);
...

CodePudding user response:

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  late String message;
  late bool isPass;
  late Future<String> data;

  MyHomePage(this.message, this.isPass, this.data);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String getData = '';

  @override
  MyHomePage get widget => super.widget;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$getData Test Demo'),
      ),
      body: Container(),
    );
  }

  getFutureData() async {
    getData = await widget.data;
    setState(() {});
  }
}

Achieve like this have used String you can use your custom class

  • Related