错误:无法将参数类型“ Future”分配给参数类型“ void Function()”

时间:2019-09-02 18:41:48

标签: flutter statelesswidget

当我将值从主页传递到源页面时,它显示错误:无法将参数类型“ Future”分配给参数类型“ void Function()”。 (在[ strong text ]处为argument_type_not_assignable lib \ home.dart:15)

我在哪里做错了?

主页-

version: 2.1
orbs:
  cypress: cypress-io/cypress@1
  react: thefrontside/react@0.1.0
workflows:
  push:
    jobs:
      - react/install
      - react/test:
          requires:
            - react/install
  build:
    jobs:
      - cypress/run:
          yarn: true
          start: yarn start
          wait-on: 'http://localhost:3000'
          no-workspace: true

下面是我要使用首页值的地方-

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

class Home extends StatefulWidget {
  int value;
  Home({this.value});
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlatButton(
          onPressed: Navigator.push(context, MaterialPageRoute(builder: (context)=>SourceScreen({value:value}))), child: null,
        ),
      ),
    );
  }
}

3 个答案:

答案 0 :(得分:4)

这个在最新版本中对我有用

 onPressed: () {
          selectHandler();
 },

答案 1 :(得分:1)

    @CopsOnRoad -- Here is the sample code that is working for me.

*Answer.dart file*
    
    import 'package:flutter/material.dart';
    
    class Answer extends StatelessWidget {
      final Function selectHandler;
    
      // ignore: use_key_in_widget_constructors
      const Answer(this.selectHandler);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          width: double.infinity,
          child: RaisedButton(
            color: Colors.grey,
            textColor: Colors.black,
            child: Text('Answer 1'),
            **onPressed: () => selectHandler()**,
          ),
        );
      }
    }
    
    *Main.dart file snippet*
    
    @override
      Widget build(BuildContext context) {
        var questions = [
          'What\'s your favorite color?',
          'What\'s your favorite animal?'
        ];
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text(questions[_questionIndex]),
            ),
            body: Column(
              children: <Widget>[
                Question(questions[_questionIndex]),
                **Answer(_answerQuestion)**,
                Answer(_answerQuestion),
                Answer(_answerQuestion),
              ],
            ),
          ),
        );
      }
    }

答案 2 :(得分:0)

替换

onPressed: Navigator.push(context, MaterialPageRoute(builder: (context) => SourceScreen({value: value}))), child: null,

使用

onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => SourceScreen({value: value}))), child: null,