【问题标题】:Got this error while passing callback function in flutter, Can anyone solve this在颤振中传递回调函数时出现此错误,任何人都可以解决这个问题
【发布时间】:2021-09-19 17:44:08
【问题描述】:

在这里,我正在尝试制作一个 Begginer 测验应用程序。 尝试为每个小部件创建一个单独的文件。 在这个过程中,使用回调函数出现错误,找不到解决方法。

'''

import 'package:flutter/material.dart';
import 'question.dart';
import 'answer.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var _questionIndex = 0;
  void _answerQuestion() {
    setState(() {
      _questionIndex = _questionIndex + 1;
     });

    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      'What\'s your choice of color ?',
      'What\'s your choice of animal'
    ];
    return MaterialApp(
       home: Scaffold(
       appBar: AppBar(
          title: (Text('Quiz time')),
        ),
        body: Column(
          children: [
        
            Question(
              questions[_questionIndex],
             ),
            Answer(_answerQuestion),
            Answer(_answerQuestion),
            Answer(_answerQuestion),
          ],
        ),
      ),
    );
  }
}

文件名= answer.dart 导入'package:flutter/material.dart';

class Answer extends StatelessWidget {

  final Function selectHandler;
  Answer(this.selectHandler);
  @override
  Widget build(BuildContext context) {
     return Container(
       width: double.infinity,
       child: ElevatedButton(
       child: Text('Answer 1'),       

       onPressed:selectHandler,

**here in selectHandler it is showing error**
      ),
    );
  }
}

''' 参数类型“Function”不能分配给参数类型“void Function()?”。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    将您的 selectHandler 类型更新为VoidCallback 应该没问题

      final VoidCallback selectHandler;
    

    【讨论】:

      【解决方案2】:

      注意:它与this 重复 你需要调用这样的函数;

      final void Function() selectHandler; // instead of final Function selectHandler;
      

      或者你也可以在下面使用。这两种解决方案是一样的;

      final VoidCallback selectHandler;
      

      【讨论】:

        【解决方案3】:

        答案很简单,你必须在 Answer.dart 文件中更新这一行。

        final Function selectHandler;
        

        将此行替换为

        final VoidCallback selectHandler;
        

        这一行将解决你的问题。

        【讨论】:

          猜你喜欢
          • 2020-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-24
          • 2016-09-19
          • 1970-01-01
          • 1970-01-01
          • 2021-08-11
          相关资源
          最近更新 更多