在空颤振下调用方法“〜/”

时间:2019-10-17 12:16:50

标签: android flutter mobile flutter-layout

当我调用倒数计时小部件时,出现此异常:

  

在构建Countdown(脏状态:_CountdownState#97b4a)时引发了以下NoSuchMethodError:   方法“〜/”在null上被调用。   接收者:null   尝试致电:〜/(3600)

     

用户创建的导致错误的小部件的祖先是       容器

     

初始状态为空

1毫秒后,我的倒计时在我的应用栏中打印出来,这很好,但是为什么?

class IneatAppBarPollWidget {
  getAppBar(String title, String logo, Candidate candidate) {
    return AppBar(
      title: Text(title),
      leading: Image.asset(
        logo,
        fit: BoxFit.contain,
        height: 32,
      ),
      actions: <Widget>[
        new Container(
          child: new Row(
            children: <Widget>[
              new Container(
                margin:EdgeInsets.only(right: 10),
                child: new Countdown(),
              ),
              new CircleAvatar(
                child: new Text(
                  '${candidate.firstname[0].toUpperCase()}.${candidate.lastname[0].toUpperCase()}',
                  style: TextStyle(fontSize: 20),
                ),
                backgroundColor: Colors.white,
              ),
            ],
          ),
          margin: EdgeInsets.only(right: 10),
        ),
      ],
    );
  }
}

class Countdown extends StatefulWidget {
  @override
  _CountdownState createState() => _CountdownState();
}

class _CountdownState extends State<Countdown> {
  Timer _timer;
  int seconds;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        constructTime(seconds),
        style: TextStyle(
            fontSize: 18, color: Colors.white, fontStyle: FontStyle.italic),
      ),
    );
  }

  String constructTime(int seconds) {
    int hour = seconds ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    return formatTime(hour) +
        ":" +
        formatTime(minute) +
        ":" +
        formatTime(second);
  }

  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  @override
  initState() {
    getDate();
    startTimer();
    super.initState();
  }

  void getDate() async {
    var now = DateTime.now();
    String creationDate = await Poll().getCreationDateToSF();
    DateTime creationDateTime = DateTime.parse(creationDate);
    seconds = creationDateTime.difference(now).inSeconds;
  }

  void startTimer() {
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      setState(() {
        seconds--;
      });
      if (seconds == 0) {
        cancelTimer();
      }
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }
}

1 个答案:

答案 0 :(得分:1)

在设置seconds之前呈现布局。您应该为second分配一个初始值。

int seconds = 0;