我在 Flutter 中遇到了一个问题:在构建 TextField 时抛出了以下断言,这让我遇到了一个奇怪的问题

Sab*_* 02 2 android widget dart flutter

我在 Flutter 中遇到了一个问题:以下断言在构建 TextField 时被抛出,这让我在短时间内遇到了一个奇怪的问题!

对于代码或错误的任何澄清,请在下面评论,我会在几分钟内回复,因为我迫不及待地解决这个问题并没有太多想法继续前进!!

我是一个非常接近 Flutter 编程的意大利男孩,我从这门课程开始。你是我唯一可以称呼的人。我会向任何能解决这个“问题”的人提供玛格丽塔披萨;)!!!

Andoid Studio返回我的错误是这样的:

I/flutter (26182): 以下断言被抛出构建 TextField(controller: I/flutter (26182): TextEditingController#e1688(TextEditingValue(text: ??, selection: TextSelection(baseOffset: -1, I/flutter (26182)) :extentOffset:-1,affinity:TextAffinity.downstream,isDirectional:false),组合:I/flutter(26182):TextRange(开始:-1,结束:-1))),启用:true,装饰:InputDecoration(hintText) :“Materia”),I/flutter(26182):自动更正:true,强制执行最大长度,onTap:空,脏,状态:_TextFieldState#73fdb):I/flutter(26182):找不到材料小部件。I/flutter (26182):TextField 小部件需要一个 Material 小部件祖先。I/flutter (26182):在材料设计中,大多数小部件在概念上都是“打印”在一张材料上的。在 Flutter 的 I/flutter (26182): 材料库中,该材料由材料小部件表示。例如,材质小部件 I/flutter (26182):渲染墨水飞溅。因此,许多材质库小部件需要 I/flutter (26182):它们上方的树中有一个材质小部件。I/flutter (26182):要引入 Material 小部件,您可以直接包含一个小部件,也可以使用包含 I/flutter (26182):材质本身的小部件,例如 Card、Dialog、Drawer 或 Scaffold。I/flutter (26182):找不到 Material 祖先的特定小部件是: I/flutter (26182):I/flutter (26182):要引入 Material 小部件,您可以直接包含一个小部件,也可以使用包含 I/flutter (26182):材质本身的小部件,例如 Card、Dialog、Drawer 或 Scaffold。I/flutter (26182):找不到 Material 祖先的特定小部件是: I/flutter (26182):I/flutter (26182):要引入 Material 小部件,您可以直接包含一个小部件,也可以使用包含 I/flutter (26182):材质本身的小部件,例如 Card、Dialog、Drawer 或 Scaffold。I/flutter (26182):找不到 Material 祖先的特定小部件是: I/flutter (26182):
TextField(controller: TextEditingController#e1688(TextEditingValue(text: ??, selection: I/flutter (26182): TextSelection(baseOffset: -1, extentOffset: -1,affinity: TextAffinity.downstream, isDirectional: I/flutter (26182) :
false), 组合: TextRange(start: -1, end: -1))), 启用: true, 装饰: I/flutter (26182): InputDecoration(hintText: "Materia"), autocorrect: true, 最大长度强制执行, onTap: null) I/flutter (26182): 这个小部件的祖先是:

...以及一长串小部件

这是我的代码,一个非常简单的输入表单,有 2 个表单,“材料”和“描述”,以及将它加载到一个名为“ AssegnoPage ”的TabBarView 的页面。我使用范围模型,下面你会找到它。ù

重点选项卡上AssegnoPageAssegnoListPageAggiungiAssegno

AssegnoPage

import 'package:flutter/material.dart';

import 'package:prova_app_book/assegno/page/aggiungi_assegno.dart'; import 'package:prova_app_book/widget/drawer.dart'; import 'assegno_list.dart'; //import '../../models/assegno.dart';

class AssegnoPage extends StatelessWidget {

  @override   Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        drawer: Drawer(child: DrawerWidget(),),
        appBar: AppBar(
          title: Text('Gestione Assegno'),
          bottom: TabBar(
              tabs: <Widget>[
                Tab(
                  icon: Icon(Icons.edit),
                  text: 'Aggiungi Assegno',
                ),
                Tab(
                  icon: Icon(Icons.book),
                  text: 'Il tuo assegno',
                ),
              ],
          ),
        ),
        body: TabBarView(children: <Widget> [
          AggiungiAssegno(),
          AssegnoListPage()
        ]),
      ),
    );   } }
Run Code Online (Sandbox Code Playgroud)

最后带有提交按钮的简单表单:

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';

import '../../scoped_models/assegno.dart';
import '../../models/assegno.dart';

class AggiungiAssegno extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _AggiungiAssegnoState();
  }
}

class _AggiungiAssegnoState extends State<AggiungiAssegno> {
  final Map<String, dynamic> _formData = {
    'materia': null,
    'assegno': null,
  };
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Widget _buildTitoloMateria(Assegno assegno) {
    return TextFormField(
      decoration: InputDecoration(hintText: 'Materia'),
      initialValue: assegno == null ? '' : assegno.materia,
      validator: (String value) {
        if (value.isEmpty) {
          return 'Il nome della materia è necessario';
        }
      },
      onSaved: (String value) {
        _formData['materia'] = value;
      },
    );
  }

  Widget _buildAssegno(Assegno assegno) {
    return TextFormField(
      decoration: InputDecoration(hintText: 'Assegno'),
      maxLines: 3,
      initialValue: assegno == null ? '' : assegno.assegno,
      validator: (String value) {
        if (value.isEmpty) {
          return 'L\'assegno è necessario';
        }
      },
      onSaved: (String value) {
        _formData['assegno'] = value;
      },
    );
  }

  void _submitForm(Function aggiungiAssegno, Function aggiornaAssegno, [int selectedAssegnoIndex]) {
    if (!_formKey.currentState.validate()) {
      return;
    }
    _formKey.currentState.save();
    if (selectedAssegnoIndex == null) {
      aggiungiAssegno(Assegno(
          materia: _formData['materia'], assegno: _formData['assegno']));
    } else {
      aggiornaAssegno(
          Assegno(
              materia: _formData['materia'], assegno: _formData['assegno']));
    }
    Navigator.pushReplacementNamed(context, '/panoramica');
  }

  Widget _buildSubmitButton() {
    return ScopedModelDescendant<AssegnoModel>(
      builder: (BuildContext context, Widget child, AssegnoModel model) {
        return RaisedButton(
          child: Text('Fatto'),
          textColor: Colors.white,
          onPressed: () =>
              _submitForm(model.aggiungiAssegno, model.aggiornaAssegno, model.selectesAssegnoIndex),
        );
      },
    );
  }

  Widget _buildPageContent(BuildContext context, Assegno assegno) {
    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 Container(
      margin: EdgeInsets.all(10.0),
      child: Form(
        key: _formKey,
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: targetPadding / 2),
          children: <Widget>[
            _buildTitoloMateria(assegno),
            SizedBox(
              height: 20.0,
            ),
            _buildAssegno(assegno),
            SizedBox(
              height: 20.0,
            ),
            _buildSubmitButton(),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<AssegnoModel>(
      builder: (BuildContext context, Widget child, AssegnoModel model) {
        final Widget pageContent = _buildPageContent(context, model.selectedAssegno);
        return model.selectesAssegnoIndex == null
            ? pageContent
            : Scaffold(
                appBar: AppBar(
                  title: Text('Aggiungi Assegno'),
                ),
                body: pageContent,
              );
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

AssegnoListPage,这里,我返回上一页,按下按钮,flutter给我上面的错误!

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';

//import '../../models/assegno.dart';
import 'aggiungi_assegno.dart';
import '../../scoped_models/assegno.dart';

class AssegnoListPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<AssegnoModel>(
      builder: (BuildContext context, Widget child, AssegnoModel model) {
        return ListView.builder(
          itemBuilder: (BuildContext context, int index) {
            return Column(
              children: <Widget>[
                ListTile(
                  leading: Icon(Icons.book),
                  title: Text(model.assegno[index].materia),
                  trailing: IconButton(
                      icon: Icon(Icons.edit),
                      onPressed: () {
                        model.selectAssegno(index);
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (BuildContext context) {
                              return AggiungiAssegno();
                            },
                          ),
                        );
                      }),
                ),
                Divider(),
              ],
            );
          },
          itemCount: model.assegno.length,
        );
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

表单中使用的范围模型:

import 'package:scoped_model/scoped_model.dart';

import '../models/assegno.dart';

class AssegnoModel extends Model{
  List <Assegno> _assegno = [];
  int _selectesAssegnoIndex;

  List<Assegno> get assegno{
    return List.from(_assegno);
  }

  int get selectesAssegnoIndex {
    return _selectesAssegnoIndex;
  }

  Assegno get selectedAssegno{
    if(_selectesAssegnoIndex == null){
      return null;
    }
    return _assegno[_selectesAssegnoIndex];
  }

  void aggiungiAssegno(Assegno assegno) {
      _assegno.add(assegno);
      _selectesAssegnoIndex = null;
    //print(_assegno);
  }

  void aggiornaAssegno(Assegno assegno) {
      _assegno[_selectesAssegnoIndex] = assegno;
      _selectesAssegnoIndex = null;
  }

  void eliminaAssegno() {
      _assegno.removeAt(_selectesAssegnoIndex);
      _selectesAssegnoIndex = null;
  }

  void selectAssegno(int index){
    _selectesAssegnoIndex = index;
  }
}
Run Code Online (Sandbox Code Playgroud)

Rém*_*let 8

异常解释了会发生什么:

TextField 小部件需要一个 Material 小部件祖先。


要引入这样的Material小部件,您有多种可能性:

  • 对话
  • 脚手架
  • 材料

例子:

Material(
  child: TextField(...),
)
Run Code Online (Sandbox Code Playgroud)