Expected a value of type 'String', but got one of type 'Null'
Asked Answered
W

5

5

I have to add new product as well as edit existing product in one screen . so I have Used didchangedependencies method by assigning the initial values to update a screen something gone wrong in my code.please help me out. so the error is enter image description here

Error is showing here:

@override
      void didChangeDependencies() {
        if (_isinit) {
          final productId = ModalRoute.of(context)!.settings.arguments as String;

      // ignore: unnecessary_null_comparison
      if (productId != null) {
        _editedproduct =
            Provider.of<Products>(context, listen: false).FindByID(productId);
        _imageUrlController.text = _editedproduct.imageUrl;
        _initValues = {
          'title': _editedproduct.title,
          'description': _editedproduct.description,
          'Price': _editedproduct.price.toString(),
          // 'imageUrl': _editedproduct.imageUrl,
          'imageUrl': '',
        };
      }
    }
    _isinit = false;
    super.didChangeDependencies();
  } 

In did change dependencies method I have tried to get the arguments i.e product ID from one page but it showing null. this is screenshot where i have pushed to edit screen product page with arguments which I was tried to fetch this arguments.
enter image description here
and this is for pushing to adding product page enter image description here

import 'dart:html';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shoppingapp/Providers/Product.dart';
import 'package:shoppingapp/Providers/Products.dart';

class EditProductScreen extends StatefulWidget {
  static const routeName = '/edit-products';
  @override
  _EditProductScreenState createState() => _EditProductScreenState();
}

class _EditProductScreenState extends State<EditProductScreen> {
  final _priceFocusNode = FocusNode();
  final _descriptionFocusNode = FocusNode();
  final _imageUrlController = TextEditingController();
  final _imageUrlFocusNode = FocusNode();
  final _form = GlobalKey<FormState>();
  var _editedproduct =
      Product(id: '', title: '', description: '', price: 0, imageUrl: '');
  var _isinit = true;

  var _initValues = {
    'title': '',
    'description': '',
    'price': '',
    'imageUrl': '',
  };
  @override
  void initState() {
    _imageUrlFocusNode.addListener(_updateImageUrl);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    if (_isinit) {
      final productId = ModalRoute.of(context)!.settings.arguments as String;

      // ignore: unnecessary_null_comparison
      if (productId != null) {
        _editedproduct =
            Provider.of<Products>(context, listen: false).FindByID(productId);
        _imageUrlController.text = _editedproduct.imageUrl;
        _initValues = {
          'title': _editedproduct.title,
          'description': _editedproduct.description,
          'Price': _editedproduct.price.toString(),
          // 'imageUrl': _editedproduct.imageUrl,
          'imageUrl': '',
        };
      }
    }
    _isinit = false;
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _imageUrlFocusNode.removeListener(_updateImageUrl);
    _priceFocusNode.dispose();
    _descriptionFocusNode.dispose();
    _imageUrlFocusNode.dispose();

    super.dispose();
  }

  void _updateImageUrl() {
    if (!_imageUrlFocusNode.hasFocus) {
      setState(() {});
    }
  }

  void _saveForm() {
    final isValid = _form.currentState!.validate();
    if (isValid) {
      return;
    }
    _form.currentState!.save();
    if (_editedproduct.id != null) {
      Provider.of<Products>(context, listen: false)
          .updateProducts(_editedproduct.id, _editedproduct);
    } else {
      Provider.of<Products>(context, listen: false).addProducts(_editedproduct);
    }

    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Edit Product'),
        actions: [
          IconButton(
            icon: Icon(Icons.save),
            onPressed: _saveForm,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Form(
          key: _form,
          child: ListView(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Title',
                ),
                initialValue: _initValues['title'],
                textInputAction: TextInputAction.next,
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Please provide a value.';
                  }
                  return null;
                },
                onFieldSubmitted: (_) {
                  FocusScope.of(context).requestFocus(_priceFocusNode);
                },
                onSaved: (value) {
                  _editedproduct = Product(
                      title: value as String,
                      price: _editedproduct.price,
                      description: _editedproduct.description,
                      imageUrl: _editedproduct.imageUrl,
                      id: _editedproduct.id,
                      isFavourite: _editedproduct.isFavourite);
                },
              ),
              TextFormField(
                initialValue: _initValues['price'],
                decoration: InputDecoration(
                  labelText: 'Price',
                ),
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.number,
                focusNode: _priceFocusNode,
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Please enter a  price ';
                  }
                  if (double.tryParse(value) == null) {
                    return 'Please Enter a Valid Number';
                  }
                  if (double.parse(value) <= 0) {
                    return 'Please Enter the number greather no than zero';
                  }
                },
                onSaved: (value) {
                  _editedproduct = Product(
                      title: _editedproduct.title,
                      price: double.parse(value!),
                      description: _editedproduct.description,
                      imageUrl: _editedproduct.imageUrl,
                      id: _editedproduct.id,
                      isFavourite: _editedproduct.isFavourite);
                },
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Description',
                ),
                initialValue: _initValues['description'],
                maxLines: 3,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.multiline,
                focusNode: _descriptionFocusNode,
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Please enter a  description ';
                  }
                  if (value.length < 10) {
                    return 'Should be at least 10 characters long.';
                  }
                  return null;
                },
                onSaved: (value) {
                  _editedproduct = Product(
                      title: _editedproduct.title,
                      price: _editedproduct.price,
                      description: value as String,
                      imageUrl: _editedproduct.imageUrl,
                      id: _editedproduct.id,
                      isFavourite: _editedproduct.isFavourite);
                },
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Container(
                    width: 100,
                    height: 100,
                    margin: EdgeInsets.only(top: 8, right: 10),
                    decoration: BoxDecoration(
                        border: Border.all(width: 1, color: Colors.grey)),
                    child: _imageUrlController.text.isEmpty
                        ? Text('Enter a URL')
                        : FittedBox(
                            child: Image.network(
                              _imageUrlController.text,
                              fit: BoxFit.cover,
                            ),
                          ),
                  ),
                  Expanded(
                    child: TextFormField(
                      decoration: InputDecoration(labelText: 'Image URl'),
                      keyboardType: TextInputType.url,
                      textInputAction: TextInputAction.done,
                      controller: _imageUrlController,
                      focusNode: _imageUrlFocusNode,
                      validator: (value) {
                        if (value!.isEmpty) {
                          return 'Please enter a  URL ';
                        }
                        if (!value.startsWith('http') &&
                            !value.startsWith('https')) {
                          return 'Please Enter a valid URL';
                        }
                        if (!value.endsWith('.png') &&
                            !value.endsWith('.jpg') &&
                            !value.endsWith('.jpeg')) {
                          return 'Please enter a valid image URL';
                        }
                        return null;
                      },
                      onFieldSubmitted: (_) {
                        _saveForm();
                      },
                      onSaved: (value) {
                        _editedproduct = Product(
                            title: _editedproduct.title,
                            price: _editedproduct.price,
                            description: _editedproduct.description,
                            imageUrl: value as String,
                            id: _editedproduct.id,
                            isFavourite: _editedproduct.isFavourite);
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Wellthoughtof answered 7/7, 2021 at 15:4 Comment(6)
which variable is null exactly, do you know?Duntson
I think in didchangedependencies method , ProductID variableWellthoughtof
you have already added null check if (productId != null) , now you should not get that exception.Duntson
so is this because of imageurl in _initvalues ?Wellthoughtof
I doubt _editedproduct providing not having all values, use null operators with upgrading flutterDuntson
I tried to print the every variable of _editedproduct but it works perfectly finedWellthoughtof
S
4

While Null-Safety is implemented, most tutorials were made before it so in your case where you are trying to check if the ModalRoute returns you a null value or not and do stuff depending on that, good old if(productId == null) won't work now. Instead you can do this:

final productId = ModalRoute.of(context)!.settings.arguments == null ? "NULL":ModalRoute.of(context)!.settings.arguments as String;

if(productId != "NULL"){
 
   //Do stuff here

}

If ModalRoute gives you null, you assign the string "NULL" to your variable productId else you just assign whatever value it returned.

Then you can simply check if the value of productId is NULL and proceed accordingly.

Simson answered 31/7, 2021 at 11:24 Comment(0)
B
2

Following the answer, Maruf Ahmed gave will work but will not display the added product. What solved the error for me was to change != null into '' annotation inside the saveForm method.

You can check the saveForm method

1

Barksdale answered 30/7, 2022 at 10:30 Comment(1)
Code snippets should be included as properly formatted text, not as an image. You can find more information on how to write good answers in the help center.Baronet
F
1

I think I am late answering this question, but my answer will help someone in the future.

Avoid casting the argument to String. This error throwing cause when pushname is called without any argument then it automatically passes null, and when null casting to String then the error happen.

Use like this line

final productId= ModalRoute.of(context)!.settings.arguments;

Then check productId null or not. If not null then convert product object to string

  if (productId != null) {
    _editedProduct =
        Provider.of<Products>(context, listen: false).findById(productId.toString());
    ...... 

  }
Fresnel answered 10/11, 2021 at 5:55 Comment(0)
R
1

In my case, the error was the same with stacktrace

Error: Expected a value of type 'String', but got one of type 'Null'
    at Object.throw_ [as throw] (http://localhost:51932/dart_sdk.js:5080:11)
    at Object.castError (http://localhost:51932/dart_sdk.js:5039:15)
    at Object.cast [as as] (http://localhost:51932/dart_sdk.js:5356:17)
    at String.as (http://localhost:51932/dart_sdk.js:46240:19)
    at Object.getProperty (http://localhost:51932/dart_sdk.js:62320:14)
    at Object.convertFirebaseDatabaseException (http://localhost:51932/packages/firebase_database_web/src/interop/database.dart.lib.js:1318:27)
    at http://localhost:51932/packages/firebase_database_web/src/interop/database.dart.lib.js:289:67
    at Object._checkAndCall (http://localhost:51932/dart_sdk.js:5279:16)
    at Object.dcall (http://localhost:51932/dart_sdk.js:5284:17)
    at ret (http://localhost:51932/dart_sdk.js:62210:21)
    at CallbackContext.onCancel (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:13442:36)
    at https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:14240:47
    at exceptionGuard (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:2000:9)
    at eventListRaise (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:12292:13)
    at eventQueueRaiseQueuedEventsMatchingPredicate (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:12267:17)
    at eventQueueRaiseEventsForChangedPath (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:12256:5)
    at Object.onComplete (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:12413:17)
    at https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:4667:32
    at PersistentConnection.onDataMessage_ (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:4920:17)
    at Connection.onDataMessage_ (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:3762:14)
    at Connection.onPrimaryMessageReceived_ (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:3756:18)
    at WebSocketConnection.onMessage (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:3658:26)
    at WebSocketConnection.appendFrame_ (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:3275:18)
    at WebSocketConnection.handleIncomingFrame (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:3323:22)
    at mySock.onmessage (https://www.gstatic.com/firebasejs/9.9.0/firebase-database.js:3222:18)

I was stuck with this for 2 days when I remembered the date limit on the default database rules have been expired:

{
  "rules": {
    ".read": "now < ...",  // YYYY-MM-DD
    ".write": "now < ...",  // YYYY-MM-DD
  }
}

So I just defined better rules and I got it working.

Reuven answered 6/9, 2022 at 14:58 Comment(0)
B
-2

Jitesh Mohite (_editedProduct.id) is the null variable inside the 'build', inside 'didchangedependencies' it's not null, it has the same value of ProductId

Barbel answered 22/7, 2021 at 15:34 Comment(1)
This does not answer the question, please ask your queries in comments of the question.Simson

© 2022 - 2024 — McMap. All rights reserved.