user9436741
user9436741

Reputation:

how to fix a non-null string must be provided to a Text widget?

I'm trying to print my card widget title in the card details page but I'm getting " A non-null String must be provided to a Text widget".

Any suggestion or help on how can I fix this?.

Model.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'),
]

Upvotes: 0

Views: 202

Answers (2)

Boris Ilic
Boris Ilic

Reputation: 11

In _CardWidgetState you have defined an empty object. That object you passed to the CardDetails page through the constructor, and on the CardDetails page you try in Text widget call item.title but it is null (without value). You need populate this object or try with hardcode string.

Same ase here: A non-null String must be provided to a Text widget

Upvotes: 1

Owczar
Owczar

Reputation: 2593

The cause is item declared in CardWidget.dart - there is no title, so item.title in CardDetails.dart is null. To fix the error you can add default value for tile field in Item class:

class Item {
  int id;
  String title;

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

Upvotes: 0

Related Questions