我是第一次使用Flutter + Dart。我基本上有以下几个类。首先,我有一个名为BottomForm类,其中有一个构建函数,当我在onPressed中调用函数类型变量时,该函数返回空问题。我有一个问题:参数类型‘ElevatedButton’不能赋值给参数类型'void function ()?‘。.dartargument_ type _not_assignable
import 'formbutton.dart';
// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final email = TextEditingController();
final password = TextEditingController();
void _logIn() {
print("Logged In.");
}
@override
void dispose() {
// Clean up the controller when the widget is disposed.
email.dispose();
password.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: TextFormField(
autocorrect: true,
controller: email,
),
),
ButtonForm(_logIn, "Hello"),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(email.text),
);
});
},
tooltip: "Show me the value",
child: Icon(Icons.text_fields),
),
);
}
}
//Define a Custom Widget
class MyCustomForm extends StatefulWidget {
@override
_MyCustomFormState createState() => _MyCustomFormState();
}我在我们的Button的主类中有一个问题。当我传递函数functionApply时;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ButtonForm extends StatelessWidget {
final Function functionApply;
final String textButton;
ButtonForm(this.functionApply, this.textButton);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(this.textButton),
onPressed: this.functionApply, // I have a problem here!!
),
);
}
}发布于 2021-05-23 13:37:01
onPressed是VoidCallback的一种
typedef VoidCallback = void Function()所以不是使用
final Function functionApply;使用
final VoidCallback functionApply;所以你的ButtonForm将会是
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ButtonForm extends StatelessWidget {
final VoidCallback functionApply;
final String textButton;
ButtonForm(this.functionApply, this.textButton);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(textButton),
onPressed: functionApply, // Problem Solved!!
),
);
}
}发布于 2021-05-23 12:36:15
试试这个:
ElevatedButton(
child: Text(this.textButton),
onPressed: () {
functionApply();
},
)发布于 2021-05-23 12:45:23
给出函数的返回类型。如果你没有提供任何返回类型,那么默认情况下返回类型为dynamic。但是onPressed函数的返回类型是空的,所以只要改变函数的减速就可以了。
final void Function() functionApply;https://stackoverflow.com/questions/67656140
复制相似问题