颤振-'initialValue == null ||控制器 == null': 不正确。表单小部件中的错误

Posted

技术标签:

【中文标题】颤振-\'initialValue == null ||控制器 == null\': 不正确。表单小部件中的错误【英文标题】:Flutter - 'initialValue == null || controller == null': is not true. error in the form widget颤振-'initialValue == null ||控制器 == null': 不正确。表单小部件中的错误 【发布时间】:2021-09-14 17:18:27 【问题描述】:

Flutter - 'initialValue == null ||控制器 == null':不正确。错误。我正在尝试在添加产品中使用的表单中编辑我想要产品详细信息的产品。但问题出在 imageUrl 上,因为它有一个 textEditing 控制器。我试过这种方法,但它对我不起作用

@override
      void didChangeDependencies() 
        if (_isinit) 
          final productId = ModalRoute.of(context)!.settings.arguments as String;
          if (productId != null) 
            _editedproduct =
                Provider.of<Products>(context, listen: false).FindByID(productId);
            _imageUrlController.text = _editedproduct.imageUrl;           //error
            _initValues = 
              'title': _editedproduct.title,
              'description': _editedproduct.description,
              'Price': _editedproduct.price.toString(),
              
              'imageUrl': '',                              //error
            ;
          
        
        _isinit = false;
        super.didChangeDependencies();
      

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;
      if (productId != null) 
        _editedproduct =
            Provider.of<Products>(context, listen: false).FindByID(productId);
        _imageUrlController.text = _editedproduct.imageUrl;           //error
        _initValues = 
          'title': _editedproduct.title,
          'description': _editedproduct.description,
          'Price': _editedproduct.price.toString(),
          
          'imageUrl': '',                              //error
        ;
      
    
    _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,
                      initialValue: _initValues['imageUrl'],    //error
                      textInputAction: TextInputAction.done,
                      controller: _imageUrlController,        //error
                      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);
                      ,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  

【问题讨论】:

ITs 不允许设置控制器和初始值。您可以使用控制器设置初始值。 【参考方案1】:

我认为错误的原因是因为您设置了控制器和初始值。您只需设置这些属性之一。初始值或控制器。每次都这样做

例如改变这个

 TextFormField(
                  decoration: InputDecoration(labelText: 'Image URl'),
                  keyboardType: TextInputType.url,
                  initialValue: _initValues['imageUrl'],    //error
                  textInputAction: TextInputAction.done,
                  controller: _imageUrlController,        //error
                  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);
                  ,
                ),

以下省略初始值

 TextFormField(
                  decoration: InputDecoration(labelText: 'Image URl'),
                  keyboardType: TextInputType.url,
                  textInputAction: TextInputAction.done,
                  controller: _imageUrlController,        //error
                  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);
                  ,
                ),

我相信这种方法应该有效

【讨论】:

感谢它对我有用

以上是关于颤振-'initialValue == null ||控制器 == null': 不正确。表单小部件中的错误的主要内容,如果未能解决你的问题,请参考以下文章

升级颤振后颤振标签栏错误“getter'key'被称为null”

颤振升级后出现错误'textBaseline!= null'

颤振和json:NoSuchMethodError:方法'[]'在null上被调用

颤振错误:'上下文!= null':不正确

颤振错误“方法'toLowerCase()'在null上被调用”

颤振测试块错误类型'Null'不是类型的子类型