【问题标题】:A non-null String must be provided to a Text widget . error shows but null-safety doesn't make it for the code必须向 Text 小部件提供非空字符串。错误显示,但 null-safety 不适用于代码
【发布时间】:2021-07-26 15:38:07
【问题描述】:

我是编程新手,并且正在学习没有 null-safety 的旧课程。我试图通过插入一个默认值来解决这个问题,但这只是让按钮上的所有文本都带有“默认值”这个词。

    // @dart=2.9



import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final Function selectHandler;
  final String answerText;

  Answer(this.selectHandler, this.answerText);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        child: RaisedButton(
          color: Colors.red.shade400,
          textColor: Colors.white,
          
          child: Text(answerText?? 'default value'),

          onPressed: selectHandler,
        ));
  }
}

编辑

Answer 类在这里被调用:

// @dart=2.9

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



class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;

  Quiz(
      {@required this.questions,
      @required this.answerQuestion,
      @required this.questionIndex});

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Question(
         questions[questionIndex]['questionText']?? "default value",
        ),
        ...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
            .map((answer) {
          return Answer(() => answerQuestion(answer['score']), answer['text']);
        }).toList()
      ],
    );
  }
}

【问题讨论】:

  • 可以分享你拨打Answer的地方吗?
  • @Jahidul Islam 我编辑了它

标签: android ios visual-studio flutter dart


【解决方案1】:

在空安全飞镖中,String 永远不会为空,因此您不能在字符串后使用 ??。但是,您可以将answerText 定义为String?,这将使其成为可为空的字符串。更多详情可以查看this website

上面的解释可以让程序运行,但是到处设置默认值并不是一个好的编码风格。当您或您的团队尝试调试您的代码时,它会带来很多麻烦。更好的做法是在启动对象时设置默认值:

class Answer extends StatelessWidget {
  final void Function()? selectHandler;
  final String answerText;

  Answer(void Function()? selectHandler, String? answerText)
      : selectHandler = selectHandler,
        answerText = answerText ?? 'default value';

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        child: RaisedButton(
          color: Colors.red.shade400,
          textColor: Colors.white,
          child: Text(answerText),
          onPressed: selectHandler,
        ));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2021-07-19
    • 2020-04-14
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多