-1

大家好,所以我试图在我的页面“product_edit”中添加一些错误检查代码来处理任何潜在的 http 响应错误

所以这是我的页面

product_edit.dart

===============================

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import '../models/product.dart';
import '../scoped-models/main.dart';
class ProductEdit extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ProductEditState();
  }
}
class _ProductEditState extends State<ProductEdit> {
  final Map<String, dynamic> _formData = {
    'title': null,
    'description': null,
    'price': null,
    'image':
        'https://cdn.pixabay.com/photo/2020/03/04/07/28/black-4900736_960_720.jpg'
  };
  //String _title;
  // String _description;
  // double _price;
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
  Widget _buildtypetextfield(Product product) {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Product Type'),
      initialValue: product == null ? '' : product.title,
      validator: (String value) {
        if (value.isEmpty) {
          return 'product type and name is required';
        }
        return null;
      },
      onSaved: (String value) {
        _formData['title'] = value;
      },
    );
  }
  Widget _builddescriptiontextfield(Product product) {
    return TextFormField(
      maxLines: 6,
      decoration: InputDecoration(labelText: 'Description'),
      initialValue: product == null ? '' : product.description,
      validator: (String value) {
        if (value.isEmpty || value.length < 10) {
          return 'product description is required,and should be 10+ characters long';
        }
        return null;
      },
      onSaved: (String value) {
        _formData['description'] = value;
      },
    );
  }
  Widget _buildpricetextfield(Product product) {
    return TextFormField(
      keyboardType: TextInputType.number,
      decoration: InputDecoration(labelText: 'Price'),
      initialValue: product == null ? '' : product.price.toString(),
      validator: (String value) {
        if (value.isEmpty ||
            !RegExp(r'^(?:[1-9]\d*|0)?(?:\.\d+)?$').hasMatch(value)) {
          return 'product price is required,and should be a number';
        }
        return null;
      },
      onSaved: (String value) {
        _formData['price'] = double.parse(value);
      },
    );
  }
  Widget _buildSubmitButton() {
    return ScopedModelDescendant<MainModel>(
      builder: (BuildContext context, Widget child, MainModel model) {
        return model.isloading
            ? Center(child: CircularProgressIndicator())
            : RaisedButton(
                child: Text('Save'),
                textColor: Colors.white,
                onPressed: () => _submitform(
                    model.addproduct,
                    model.updateproduct,
                    model.selectproduct,
                    model.selectedProductIndex),
              );
      },
    );
  }
  Widget _buildPageContent(BuildContext context, Product product) {
    final double deviceWidth = MediaQuery.of(context).size.width;
    final double targetWidth = deviceWidth > 550.0 ? 500.0 : deviceWidth * 0.95;
    final double targetPadding = deviceWidth - targetWidth;
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        margin: EdgeInsets.all(10.0),
        child: Form(
          key: _formkey,
          child: ListView(
            padding: EdgeInsets.symmetric(horizontal: targetPadding / 2),
            children: <Widget>[
              _buildtypetextfield(product),
              _builddescriptiontextfield(product),
              _buildpricetextfield(product),
              SizedBox(
                height: 10.0,
              ),
              _buildSubmitButton(),
            ],
          ),
        ),
      ),
    );
  }
  void _submitform(
      Function addproduct, Function updateproduct, Function setSelectedProduct,
      [int selectedproductIndex]) {
    if (!_formkey.currentState.validate()) {
      return;
    }
    _formkey.currentState.save();
    //final Map<String, dynamic> product = {
    // 'title': _title,
    // 'description': _description,
    // 'price': _price,
    // 'image':
    //     'https://cdn.pixabay.com/photo/2020/03/04/07/28/black-4900736_960_720.jpg'
    // };
    if (selectedproductIndex == -1) {
      addproduct(_formData['title'], _formData['description'],
              _formData['image'], _formData['price'])
          .then((_) => Navigator.pushReplacementNamed(context, '/products')
              .then((_) => setSelectedProduct(null)));
    } else {
      updateproduct(_formData['title'], _formData['description'],
              _formData['image'], _formData['price'])
          .then((_) => Navigator.pushReplacementNamed(context, '/products')
              .then((_) => setSelectedProduct(null)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<MainModel>(
      builder: (BuildContext context, Widget child, MainModel model) {
        final Widget pageContent =
            _buildPageContent(context, model.selectedproduct);
        return model.selectedProductIndex == -1
            ? pageContent
            : Scaffold(
                appBar: AppBar(
                  title: Text('Edit Product'),
                ),
                body: pageContent,
              );
      },
    );
  }
}

================ 并且错误发生在“_submitform”功能块中,因为我在显示对话框小部件中键入参数上下文, 这是错误的捕获, 这是功能, 非常感谢大家, 先谢谢了

_提交表格

 void _submitform(
          Function addproduct, Function updateproduct, Function setSelectedProduct,
          [int selectedproductIndex]) {
        if (!_formkey.currentState.validate()) {
          return;
        }
        _formkey.currentState.save();
        //final Map<String, dynamic> product = {
        // 'title': _title,
        // 'description': _description,
        // 'price': _price,
        // 'image':
        //     'https://cdn.pixabay.com/photo/2020/03/04/07/28/black-4900736_960_720.jpg'
        // };
        if (selectedproductIndex == -1) {
          addproduct(_formData['title'], _formData['description'],
                  _formData['image'], _formData['price'])
              .then((bool success) {
            if (success) {
              Navigator.pushReplacementNamed(context, '/products')
                  .then((_) => setSelectedProduct(null));
            } else {
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: Text('something went wrong'),
                      content: Text('please try again!'),
                      actions: <Widget>[
                        FlatButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: Text('Okay'),
                        )
                      ],
                    );
                  });
            }
          });
        } else {
          updateproduct(_formData['title'], _formData['description'],
                  _formData['image'], _formData['price'])
              .then((_) => Navigator.pushReplacementNamed(context, '/products')
                  .then((_) => setSelectedProduct(null)));
        }
      }
4

1 回答 1

0

showDialogNavigator要求BuildContext. 在您的_submitform函数中添加一个参数 : BuildContext

               void _submitform(BuildContext context,
                  Function addproduct, Function updateproduct, Function setSelectedProduct,
                  [int selectedproductIndex]) { 
                    // code 
               }

在函数中传递BuildContext这里并在and中_submitform使用它。您再次在函数内部使用函数。所以再次在函数中添加一个参数并将其传递给函数等等。最终你必须将函数传递给函数。这是根据您当前代码的流程。contextshowDialogNavigator_submitform_buildSubmitButtonBuildContext_buildSubmitButton_submitformBuildContextbuild_submitform

于 2020-05-06T06:42:11.967 回答