【问题标题】:how to fix a non-null string must be provided to a Text widget?如何修复非空字符串必须提供给文本小部件?
【发布时间】:2021-03-07 13:37:05
【问题描述】:

我正在尝试在卡片详细信息页面中打印卡片小部件标题,但我收到“必须向文本小部件提供非空字符串”。

关于如何解决此问题的任何建议或帮助?

模型.dart

class Item {
  int id;
  String title;

  Item(
      {this.id, this.title });
}

CardWidget.dart

import 'package:maxis_mobile/ui/screens/cardDetails-screen.dart';
import 'cardModel.dart';

class _CardWidgetState extends State<CardWidget> {
  final item = Item();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: Card(
          child: InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => CardDetails(item: item), //not sure this is right.
                  ));
            },
            child: Column(children: [
              Container(
                child: Row(
                  children: [
                    Container(
                      child: Text(
                        widget.title,  // Card Title
                        ),
                      ),
                    ),

CardDetails.dart

import 'package:flutter/material.dart';
import '../shared/cardModel.dart';

class CardDetails extends StatelessWidget {
  final Item item;

  CardDetails({Key key, @required this.item}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(item.title),
    );
  }
}

DummyData.dart

    List<Item> items = [
      Item(id: 0, title: '1. US Daily Retail Delivery By Brands'),
]

【问题讨论】:

  • 你在哪里使用_CardWidgetState中的虚拟数据?您在 _CardWidgetState 中创建了一个 Item 变量,但没有指定标题,这就是您传递给 CardDetails 屏幕的内容。

标签: flutter dart mobile flutter-layout flutter-animation


【解决方案1】:

您在 _CardWidgetState 中定义了一个空对象。您通过构造函数传递给 CardDetails 页面的该对象,并在 CardDetails 页面上尝试在 Text 小部件中调用 item.title 但它为空(没有值)。您需要填充此对象或尝试使用硬编码字符串。

这里也一样:A non-null String must be provided to a Text widget

【讨论】:

  • 嗨,鲍里斯,对不起,我忘了提到我有提供 cardWidget 的所有标题的虚拟数据,所以请你再看看我的代码。谢谢
  • 您有 2 个选项:1. 在 _CardWidgetState 中替换项目列表并传入构造函数 CardDetails(item: items[0]),2. 在 _CardWidgetState 中您需要初始化您的项目 final item = Item( id: 1, title: "第一项");
【解决方案2】:

原因是在CardWidget.dart 中声明了item - 没有标题,所以CardDetails.dart 中的item.title 为空。要修复该错误,您可以在 Item 类中为 tile 字段添加默认值:

class Item {
  int id;
  String title;

  Item({this.id, this.title = ''}) : assert(title != null);
}

【讨论】:

  • 嗨,Owczar,我有 dummyData.dart 文件,它提供了所有的虚拟标题,所以请你再看看我的代码。
  • 是的,但仍然:_CardWidgetState 类中有 item 最终字段。以这种方式初始化的字段总是有一个 Item 类的对象,其数据为空(因为行:final item = Item();)。您可以将此字段移动到CardWidget,并通过widget.item_CardWidgetState 类中访问它。
猜你喜欢
  • 2021-08-29
  • 2021-05-11
  • 2020-08-10
  • 2020-12-07
  • 2020-07-09
  • 2021-10-11
  • 2021-07-19
  • 2022-11-17
相关资源
最近更新 更多