热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Flutter-该方法在null上被调用

如何解决《Flutter-该方法在null上被调用》经验,为你挑选了1个好方法。

我正在编写一个应用程序,该应用程序通过一个水平方向listView和一个垂直方向在同一视图中显示两个媒体流listView。我目前正在listView使用一些漂亮的样板实现信息的底层,可以在这里找到。

我是新手,相信我的代码有些混乱,总之,我收到了错误;

flutter: The following NoSuchMethodError was thrown building Builder:
flutter: The method 'loadCurrencies' was called on null.
flutter: Receiver: null
flutter: Tried calling: loadCurrencies()

试图执行代码时,发现这里在home_page_view.dart到上述样板。

这是我用来激发错误的代码;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:to_be_deleted/data/crypto_data.dart';
import 'package:to_be_deleted/modules/crypto_presenter.dart';
import 'dart:async';
import 'dart:io';
import 'background.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
  title: 'Flutter Demo',
  theme: new ThemeData(
    primarySwatch: Colors.blue,
  ),
  debugShowCheckedModeBanner: false,
  home: new MyHomePage(title: 'Popular'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State {
CryptoListPresenter _presenter;
  List _currencies;
  bool _isLoading;
  final List _colors = [Colors.blue, Colors.indigo, Colors.red];
List items = [
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
"Item 7",
"Item 8"
];



  var refreshKey = new GlobalKey();

  @override
  void initState() {
    super.initState();
    _isLoading = true;
    _presenter.loadCurrencies();
    refreshList();
  }

    Future refreshList() async {
    refreshKey.currentState?.show(atTop: false);
    await new Future.delayed(new Duration(seconds: 1));
      _presenter.loadCurrencies();
      Scaffold.of(context).showSnackBar(
            new SnackBar(
              duration: new Duration(seconds: 3),
              backgroundColor: Colors.black,
              content: new Text(
                    'Refresh available every 60 seconds',
                    textAlign: TextAlign.center,
                  ),
              ),
            );
    setState(() {
    });
    return null;
  }

@override
Widget build(BuildContext context) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;

  Widget _getSubtitleText(String priceUSD, String percentageChange) {
    TextSpan priceTextWidget = new TextSpan(
        text: "\$$priceUSD\n", style: new TextStyle(color: Colors.black));
    String percentageChangeText = "1 hour: $percentageChange%";
    TextSpan percentageChangeTextWidget;

    if (double.parse(percentageChange) > 0) {
      percentageChangeTextWidget = new TextSpan(
          text: percentageChangeText,
          style: new TextStyle(color: Colors.green ));
    } else {
      percentageChangeTextWidget = new TextSpan(
          text: percentageChangeText, style: new TextStyle(color: Colors.red));
    }

    return new RichText(
        text: new TextSpan(
            children: [priceTextWidget, percentageChangeTextWidget]));
  }

  ListTile _getListItemUi(Crypto currency, MaterialColor color) {
    return new ListTile(
      leading: new Image.asset(
        "cryptoiconsBlack/"+currency.symbol.toLowerCase()+"@2x.png",
        width: 64.0,
        height: 64.0,
        ),
      title: new Text(currency.name,
          style: new TextStyle(fontWeight: FontWeight.bold)),
      subtitle:
      _getSubtitleText(currency.price_usd, currency.percent_change_1h),
      isThreeLine: true,
    );
  }

final headerList = new ListView.builder(
  itemBuilder: (context, index) {
    EdgeInsets padding = index == 0?const EdgeInsets.only(
        left: 20.0, right: 10.0, top: 4.0, bottom: 30.0):const EdgeInsets.only(
        left: 10.0, right: 10.0, top: 4.0, bottom: 30.0);

    return new Padding(
      padding: padding,
      child: new InkWell(
        onTap: () {
          print('Card selected');
        },
        child: new Container(
          decoration: new BoxDecoration(
            borderRadius: new BorderRadius.circular(10.0),
            color: Colors.lightGreen,
            boxShadow: [
              new BoxShadow(
                  color: Colors.black.withAlpha(70),
                  offset: const Offset(3.0, 10.0),
                  blurRadius: 15.0)
            ],
            image: new DecorationImage(
              image: new ExactAssetImage(
                  'assets/img_${index%items.length}.jpg'),
              fit: BoxFit.fitHeight,
            ),
          ),
        //height: 200.0,
          width: 200.0,
          child: new Stack(
            children: [
              new Align(
                alignment: Alignment.bottomCenter,
                child: new Container(
                    decoration: new BoxDecoration(
                        color: const Color(0xFF273A48),
                        borderRadius: new BorderRadius.only(
                            bottomLeft: new Radius.circular(10.0),
                            bottomRight: new Radius.circular(10.0))),
                    height: 30.0,
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        new Text(
                          '${items[index%items.length]}',
                          style: new TextStyle(color: Colors.white),
                        )
                      ],
                    )),
              )
            ],
          ),
        ),
      ),
    );
  },
  scrollDirection: Axis.horizontal,
  itemCount: items.length,
);

final body = new Scaffold(
  appBar: new AppBar(
    title: new Text(widget.title),
    elevation: 0.0,
    backgroundColor: Colors.transparent,
    actions: [
      new IconButton(icon: new Icon(Icons.shopping_cart, color: Colors.white,), onPressed: (){})
    ],
  ),
  backgroundColor: Colors.transparent,
  body: new Container(
    child: new Stack(
      children: [
        new Padding(
          padding: new EdgeInsets.only(top: 10.0),
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              new Align(
                alignment: Alignment.centerLeft,
                child: new Padding(
                    padding: new EdgeInsets.only(left: 8.0),
                    child: new Text(
                      'Trending News',
                      style: new TextStyle(color: Colors.white70),
                    )),
              ),
              new Container(
                  height: 300.0, width: _width, child: headerList),
              new Expanded(child:
              ListView.builder(itemBuilder: (context, index) {
                return new ListTile(
                  title: new Column(
                    children: [
                      new Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                               new Container(
                                margin: const EdgeInsets.all(10.0),
                                  child: new Column(
                                    children: [
                                      new Flexible(
                                        child: new ListView.builder(
                                          itemCount: _currencies.length,
                                          itemBuilder: (BuildContext context, int index) {
                                            final int i = index ~/ 2;
                                            final Crypto currency = _currencies[i];
                                            final MaterialColor color = _colors[i % _colors.length];
                                            if (index.isOdd) {
                                              return new Divider(color: Colors.grey);
                                            }
                                            return _getListItemUi(currency, color);
                                          },
                                        ),
                                      )
                                    ],
                                  )
                                ),
                          new SizedBox(
                            width: 8.0,
                          ),
                          new Expanded(
                              child: new Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.start,
                                children: [
                                  new Text(
                                    'My item header',
                                    style: new TextStyle(
                                        fontSize: 14.0,
                                        color: Colors.black87,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  new Text(
                                    'Item Subheader goes here\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry',
                                    style: new TextStyle(
                                        fontSize: 12.0,
                                        color: Colors.black54,
                                        fontWeight: FontWeight.normal),
                                  )
                                ],
                              )),
                          new Icon(
                            Icons.shopping_cart,
                            color: const Color(0xFF273A48),
                          )
                        ],
                      ),
                      new Divider(),
                    ],
                  ),
                );
              }))
            ],
          ),
        ),
      ],
    ),
  ),
);








  return new Container(
    decoration: new BoxDecoration(
      color: const Color(0xFF273A48),
    ),
    child: new Stack(
      children: [
        new CustomPaint(
          size: new Size(_width, _height),
          painter: new Background(),
        ),
        body,
      ],
    ),
  );
  }
}

这是我初始化应用程序后模拟器的外观

感谢您的帮助,如果您需要更多代码,请告诉我。



1> rmtmckenzie..:

您有一个,CryptoListPresenter _presenter但从未初始化它。您应该在声明它时或在您的声明中initState()(或另一个需要但需要先调用的适当方法)执行此操作。

我发现有帮助的一件事是,如果我知道某个成员在功能上是“最终的”,则可以将其实际设置为最终的,这样分析器会抱怨它尚未初始化。

编辑:

我看到diegoveloper击败了我以回答这个问题,并且OP要求跟进。

@Jake-我们很难知道确切的CryptoListPresenter是什么,但是取决于确切的CryptoListPresenter实际上,通常您会这样做final CryptoListPresenter _presenter = new CryptoListPresenter(...);,或者

CryptoListPresenter _presenter;

@override
void initState() {
  _presenter = new CryptoListPresenter(...);
}


推荐阅读
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文介绍了响应式页面的概念和实现方式,包括针对不同终端制作特定页面和制作一个页面适应不同终端的显示。分析了两种实现方式的优缺点,提出了选择方案的建议。同时,对于响应式页面的需求和背景进行了讨论,解释了为什么需要响应式页面。 ... [详细]
  • 本文介绍了贝叶斯垃圾邮件分类的机器学习代码,代码来源于https://www.cnblogs.com/huangyc/p/10327209.html,并对代码进行了简介。朴素贝叶斯分类器训练函数包括求p(Ci)和基于词汇表的p(w|Ci)。 ... [详细]
  • Apple iPad:过渡设备还是平板电脑?
    I’vebeenagonizingoverwhethertopostaniPadarticle.Applecertainlydon’tneedmorepublicityandthe ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Android日历提醒软件开源项目分享及使用教程
    本文介绍了一款名为Android日历提醒软件的开源项目,作者分享了该项目的代码和使用教程,并提供了GitHub项目地址。文章详细介绍了该软件的主界面风格、日程信息的分类查看功能,以及添加日程提醒和查看详情的界面。同时,作者还提醒了读者在使用过程中可能遇到的Android6.0权限问题,并提供了解决方法。 ... [详细]
  • 本文讨论了在使用Git进行版本控制时,如何提供类似CVS中自动增加版本号的功能。作者介绍了Git中的其他版本表示方式,如git describe命令,并提供了使用这些表示方式来确定文件更新情况的示例。此外,文章还介绍了启用$Id:$功能的方法,并讨论了一些开发者在使用Git时的需求和使用场景。 ... [详细]
  • 本文介绍了协程的概念和意义,以及使用greenlet、yield、asyncio、async/await等技术实现协程编程的方法。同时还介绍了事件循环的作用和使用方法,以及如何使用await关键字和Task对象来实现异步编程。最后还提供了一些快速上手的示例代码。 ... [详细]
  • 1简介本文结合数字信号处理课程和Matlab程序设计课程的相关知识,给出了基于Matlab的音乐播放器的总体设计方案,介绍了播放器主要模块的功能,设计与实现方法.我们将该设 ... [详细]
  • java线程池的实现原理源码分析
    这篇文章主要介绍“java线程池的实现原理源码分析”,在日常操作中,相信很多人在java线程池的实现原理源码分析问题上存在疑惑,小编查阅了各式资 ... [详细]
  • SoIhavealoopthatrunsperfectforeventsandonlyshowsfutureposts.TheissueisthatIwould ... [详细]
author-avatar
潇湘江陵
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有