按下按钮时引发NoSuchMethod异常

时间:2019-11-10 10:26:26

标签: flutter

你好,我正在学习Flutter,我正在按照一本书上的教程来构建一个简单的应用程序。我正在构建的应用具有明暗模式。点击在明暗模式之间切换的应用程序时,出现异常。我的main.dart文件如下所示:

import 'dart:ui';

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

void main() => runApp(new AppWidget());

class AppWidget extends StatefulWidget {

  AppWidget(){
    debugPrint("AppWidget - constructor - " + hashCode.toString());
  }

  @override
  _AppWidgetState createState() {
    debugPrint("AppWidget - createState - " + hashCode.toString());
    return _AppWidgetState();
  }
}

class _AppWidgetState extends State<AppWidget>{

  bool _bright = false;

  _brightnessCallback(){
    setState(() {
      _bright = ! _bright;
    });
  }

  @override
  Widget build(BuildContext context) {

    debugPrint("_AppWidgetState - build - " + hashCode.toString());
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        brightness: _bright ? Brightness.light : Brightness.dark,
      ),
      home: FlowerWidget(
        imageSrc : _bright ? "assets/images/light.jpg" : "assets/images/dark.jpg",
        brightnessCallback: _brightnessCallback(),
      ),
    );
  }

}

class FlowerWidget extends StatefulWidget{
  final String imageSrc;
  final VoidCallback brightnessCallback;
  FlowerWidget({Key key, this.imageSrc, this.brightnessCallback}) : super(key: key){
    debugPrint("FlowerWidget - constructor - " + hashCode.toString());
  }

  @override
  State<StatefulWidget> createState() {
    debugPrint("FlowerWidget - createState - " +hashCode.toString()); return _FlowerWidgetState();
  }
}

class _FlowerWidgetState extends State<FlowerWidget> {
  double _blur=0;

  _FlowerWidgetState(){
    debugPrint("_FlowerWidgetState - constructor - " +hashCode.toString());
  }

  @override
  initState() {
    debugPrint("_FlowerWidgetState - initState - " +hashCode.toString()); 
    }

  @override
  void didChangeDependencies() {
    debugPrint(
    "_FlowerWidgetState - didChangeDependencies - " +hashCode.toString()); 
    }

  @override
  void didUpdateWidget(Widget oldWidget) {
    debugPrint("_FlowerWidgetState - didUpdateWidget - " +hashCode.toString());
    // The flower image has changed, so reset the blur.
    _blur = 0;
  }

  void _blurMore(){
    setState(() {
      _blur += 0.5;
    });
  }

  @override
  Widget build(BuildContext context) {
   debugPrint("_FlowerWidgetState - build - " +hashCode.toString());
   return Scaffold(
     appBar: new AppBar(
       title: new Text("Flowers"),
       actions: <Widget>[
         new IconButton(
           icon: new Icon(Icons.refresh),
           onPressed: (){
             widget.brightnessCallback();
           },
         )
       ],
     ),
     body: new Container(
       decoration: new BoxDecoration(
        color: Theme.of(context).backgroundColor,
        image: new DecorationImage(
          image: AssetImage(widget.imageSrc),
          fit: BoxFit.cover, 
        ),
       ),
       child: new BackdropFilter(
         filter: new ImageFilter.blur(sigmaX: _blur, sigmaY: _blur),
         child: new Container(
           decoration: new BoxDecoration(
             color: Colors.white.withOpacity(0.0)
           ),
         ),
       ),
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: _blurMore,
       tooltip: 'Blur More',
       child: Icon(Icons.add),
     ),
   );
  }
}

debugprint有许多功能仅用于学习目的。我得到的异常看起来像:

════════ Exception caught by gesture ═══════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'call' was called on null.
Receiver: null
Tried calling: call()

当我在build类的_FlowerWidgetState方法中按下刷新图标时,抛出异常。我正在尝试消除此异常。 预先感谢。

1 个答案:

答案 0 :(得分:0)

这是因为在构建FlowerWidget时传递的是回调函数值,而不是对回调的引用。

class StackClass { constructor(p1, p2) { this.data = { p1, p2, accessToken: null, expiresIn: null, tokenType: null }; } async getData() { try { await isTokenValid(this); await fetch("url2 with this.data.accessToken"); } catch (err) { // or you can just avoid the `try`/`catch` altogether, // and have the consumer of getData handle problems console.log(err); } } } function isTokenValid(stack) { if (new Date() >= stack.data.expiresIn) { // Generate a new Token return getToken(stack); } // else - Do nothing and use current token saved in this.data.accessToken } async function getToken(stack) { const fetchResponse = await fetch( "url with this.data.p1 and this.data.p2" ); const fetchData = await fetchResponse.json(); if (fetchData.status != 200) { throw new Error('error'); } else { // get the token and save it in this.data stack.data.accessToken = fetchData.access_token; stack.data.expiresIn = fetchData.expires_in; stack.data.tokenType = fetchData.token_type; } }

所以,您要做的就是传递函数名称,而不要使用括号

FlowerWidget( imageSrc : _bright ? "assets/images/light.jpg" : "assets/images/dark.jpg", brightnessCallback: _brightnessCallback(), )