Flutter 在从抽屉导航时引发生成错误期间调用setState()或markNeedsBuild()

Flutter 在从抽屉导航时引发生成错误期间调用setState()或markNeedsBuild(),flutter,Flutter,我正在尝试建立一个应用程序,它有两个页面,即添加人页面和列表人页面。我的应用程序中有一个抽屉,如下面的代码所示。我正在尝试从抽屉导航到添加人员和列表人员页面,如下所示: import 'package:flutter/material.dart'; import 'dart:async'; import 'package:track_aquintances/listPerson.dart'; class Formscreen extends StatefulWidget{ @overrid

我正在尝试建立一个应用程序,它有两个页面,即添加人页面和列表人页面。我的应用程序中有一个抽屉,如下面的代码所示。我正在尝试从抽屉导航到添加人员和列表人员页面,如下所示:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:track_aquintances/listPerson.dart';

class Formscreen extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return FormscreenState();
  }

}

class FormscreenState extends State<Formscreen>{
  DateTime _selectedDate = DateTime.now();

  Widget _buildDateFIeld(){
    return Container(
      padding: const EdgeInsets.all(10),
      child: Center(
        child: Row(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  Text(
                    "When did you meet this person?",
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Montserrat'
                    ),
                  ),
                ],
              )
            )
          ],
        ),
      ),
    );
  }

  Widget _buildNameField(){
    return TextField(
      decoration: InputDecoration(
        icon: Icon(Icons.person),
        labelText: 'Name',
        labelStyle: TextStyle(
          fontFamily: 'Montserrat',
          fontWeight: FontWeight.bold,
          color: Colors.grey
        )
      ),
    );
  }

  Widget _builPhoneField(){
    return TextField(
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        icon: Icon(Icons.phone),
        labelText: 'Phone Number',
        labelStyle: TextStyle(
          fontFamily: 'Montserrat',
          fontWeight: FontWeight.bold,
          color: Colors.grey
        )
      ),
    );
  }

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != _selectedDate)
      setState(() {
        _selectedDate = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: Text(
            "Track Acquintances",
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.bold
            ),
          ),
        ),
      ),
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            DrawerHeader(
              decoration: BoxDecoration(
                gradient: LinearGradient(colors: <Color>[ 
                  Colors.teal, Colors.tealAccent
                  ])
              ),
              child: Container(
                child: Column(
                  children: <Widget>[
                    Material(
                      elevation: 10,
                      borderRadius: BorderRadius.all(Radius.circular(50.0)),
                      child: Image.asset('images/corona.JPG', width: 100, height: 100),
                    )
                  ],
                ),
              ),
            ),
            CustomListTile('Add Person', Icons.add, addTapped()),
            CustomListTile('View added People', Icons.people, listTapped(context)),
          ],
        ),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            child: Stack(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(15.0, 40.0, 0.0, 0.0),
                  child: Text(
                    'Add Person',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 40.0,
                      color: Colors.teal,
                      fontWeight: FontWeight.bold,
                      fontFamily: 'Montserrat'
                    ),
                  ),
                )
              ],
            )
          ),
          Container(
            padding: EdgeInsets.only(top: 35.0, left: 20.0),
            child: Column(
              children: <Widget>[
                _buildDateFIeld(),
                RaisedButton(
                onPressed: () => _selectDate(context),
                child: Text(
                  'Select date',
                  style: TextStyle(
                      fontFamily: 'Montserrat'
                    ),
                  )
                ),
                _buildNameField(),
                SizedBox(height: 10.0,),
                _builPhoneField(),
                SizedBox(height: 25.0,),
                Container(
                  height: 40.0,
                  child: Material(
                    borderRadius: BorderRadius.circular(20.0),
                    shadowColor: Colors.greenAccent,
                    color: Colors.teal,
                    elevation: 7.0,
                    child: GestureDetector(
                      onTap: () {},
                      child: Center(
                        child: Text(
                          'Add',
                          style: TextStyle(
                            color: Colors.white,
                            fontFamily: 'Montserrat',
                            fontWeight: FontWeight.bold
                          ),
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      )
    );
  }
}
addTapped(){

}

listTapped(context){
    Navigator.of(context).pop();
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => ListPerson()
    ));
}


class CustomListTile extends StatelessWidget{
  final String _name;
  final IconData _icon;
  final Function onTap;

  CustomListTile(this._name, this._icon, this.onTap);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.fromLTRB(9, 0, 9, 0),
      child: Container(
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(color: Colors.grey))
        ),
        child: InkWell(
          splashColor: Colors.teal,
          onTap: () => onTap,
          child: Container(
            height: 50,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Icon(_icon),
                    Padding(
                      padding: EdgeInsets.all(10),
                      child: Text(
                      _name,
                      style: TextStyle(
                        fontSize: 16,
                        fontFamily: 'Montserrat'
                      ),
                    ),
                  )
                  ],
                )
              ],
            ),
          )
        ),
      )
    );
  }
}

任何帮助都将不胜感激。提前谢谢。

您可以复制下面的粘贴运行完整代码
listTapped(context)
表示执行
listTapped
,因此需要使用
listTapped
只传递函数地址

CustomListTile('View added People', Icons.people, listTapped),
并在
InWell
onTap

代码片段

listTapped(BuildContext context) async {
  print("listTapped");
  //Navigator.of(context).pop();
  await Navigator.of(context)
      .push(MaterialPageRoute(builder: (context) => ListPerson()));
  Navigator.of(context).pop();
}
...
child: InkWell(
              splashColor: Colors.teal,
              onTap: () => onTap(context),
工作演示

完整代码

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

class Formscreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return FormscreenState();
  }
}

class FormscreenState extends State<Formscreen> {
  DateTime _selectedDate = DateTime.now();

  Widget _buildDateFIeld() {
    return Container(
      padding: const EdgeInsets.all(10),
      child: Center(
        child: Row(
          children: <Widget>[
            Expanded(
                child: Column(
              children: <Widget>[
                Text(
                  "When did you meet this person?",
                  style: TextStyle(fontSize: 16, fontFamily: 'Montserrat'),
                ),
              ],
            ))
          ],
        ),
      ),
    );
  }

  Widget _buildNameField() {
    return TextField(
      decoration: InputDecoration(
          icon: Icon(Icons.person),
          labelText: 'Name',
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.bold,
              color: Colors.grey)),
    );
  }

  Widget _builPhoneField() {
    return TextField(
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
          icon: Icon(Icons.phone),
          labelText: 'Phone Number',
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.bold,
              color: Colors.grey)),
    );
  }

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != _selectedDate)
      setState(() {
        _selectedDate = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(
            child: Text(
              "Track Acquintances",
              style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'Montserrat',
                  fontWeight: FontWeight.bold),
            ),
          ),
        ),
        drawer: Drawer(
          child: ListView(
            children: <Widget>[
              DrawerHeader(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: <Color>[Colors.teal, Colors.tealAccent])),
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Material(
                        elevation: 10,
                        borderRadius: BorderRadius.all(Radius.circular(50.0)),
                        child: Image.asset('images/corona.JPG',
                            width: 100, height: 100),
                      )
                    ],
                  ),
                ),
              ),
              CustomListTile('Add Person', Icons.add, addTapped),
              CustomListTile('View added People', Icons.people, listTapped),
            ],
          ),
        ),
        body: ListView(
          children: <Widget>[
            Container(
                child: Stack(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(15.0, 40.0, 0.0, 0.0),
                  child: Text(
                    'Add Person',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: 40.0,
                        color: Colors.teal,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Montserrat'),
                  ),
                )
              ],
            )),
            Container(
              padding: EdgeInsets.only(top: 35.0, left: 20.0),
              child: Column(
                children: <Widget>[
                  _buildDateFIeld(),
                  RaisedButton(
                      onPressed: () => _selectDate(context),
                      child: Text(
                        'Select date',
                        style: TextStyle(fontFamily: 'Montserrat'),
                      )),
                  _buildNameField(),
                  SizedBox(
                    height: 10.0,
                  ),
                  _builPhoneField(),
                  SizedBox(
                    height: 25.0,
                  ),
                  Container(
                    height: 40.0,
                    child: Material(
                      borderRadius: BorderRadius.circular(20.0),
                      shadowColor: Colors.greenAccent,
                      color: Colors.teal,
                      elevation: 7.0,
                      child: GestureDetector(
                        onTap: () {},
                        child: Center(
                          child: Text(
                            'Add',
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ));
  }
}

addTapped() {
  print("addTapped");
}

listTapped(BuildContext context) async {
  print("listTapped");
  //Navigator.of(context).pop();
  await Navigator.of(context)
      .push(MaterialPageRoute(builder: (context) => ListPerson()));
  Navigator.of(context).pop();
}

class CustomListTile extends StatelessWidget {
  final String _name;
  final IconData _icon;
  final Function onTap;

  CustomListTile(this._name, this._icon, this.onTap);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: EdgeInsets.fromLTRB(9, 0, 9, 0),
        child: Container(
          decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Colors.grey))),
          child: InkWell(
              splashColor: Colors.teal,
              onTap: () => onTap(context),
              child: Container(
                height: 50,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Icon(_icon),
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            _name,
                            style: TextStyle(
                                fontSize: 16, fontFamily: 'Montserrat'),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              )),
        ));
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Formscreen(),
    );
  }
}

class ListPerson extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("List Person"),
        ),
        body: Text("ListPerson"));
  }
}
导入“包装:颤振/材料.省道”;
导入“dart:async”;
类Formscreen扩展StatefulWidget{
@凌驾
状态createState(){
返回FormscreenState();
}
}
类FormscreenState扩展了状态{
DateTime _selectedDate=DateTime.now();
小部件_buildDateFIeld(){
返回容器(
填充:常量边集。全部(10),
儿童:中心(
孩子:排(
儿童:[
扩大(
子:列(
儿童:[
正文(
“你什么时候认识这个人的?”,
样式:TextStyle(fontSize:16,fontFamily:“蒙特塞拉特”),
),
],
))
],
),
),
);
}
小部件_buildNameField(){
返回文本字段(
装饰:输入装饰(
图标:图标(Icons.person),
labelText:'名称',
标签样式:文本样式(
fontFamily:“蒙特塞拉特”,
fontWeight:fontWeight.bold,
颜色:颜色。灰色),
);
}
小部件_builPhoneField(){
返回文本字段(
键盘类型:TextInputType.number,
装饰:输入装饰(
图标:图标(Icons.phone),
labelText:'电话号码',
标签样式:文本样式(
fontFamily:“蒙特塞拉特”,
fontWeight:fontWeight.bold,
颜色:颜色。灰色),
);
}
Future\u selectDate(BuildContext上下文)异步{
选择的最终日期时间=等待showDatePicker(
上下文:上下文,
初始日期:\您选择的日期,
firstDate:DateTime(2015年8月),
lastDate:DateTime(2101));
如果(已拾取!=null&&picked!=\u selectedDate)
设置状态(){
_selectedDate=已拾取;
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:中心(
子:文本(
“追踪获得”,
样式:TextStyle(
颜色:颜色,白色,
fontFamily:“蒙特塞拉特”,
fontWeight:fontWeight.bold),
),
),
),
抽屉(
子:ListView(
儿童:[
抽屉阅读器(
装饰:盒子装饰(
梯度:线性梯度(
颜色:[colors.teal,colors.tealacent]),
子:容器(
子:列(
儿童:[
材料(
标高:10,
borderRadius:borderRadius.all(半径.圆形(50.0)),
子项:Image.asset('images/corona.JPG',
宽度:100,高度:100),
)
],
),
),
),
CustomListTile('Add Person',Icons.Add,addTapped),
CustomListTile('查看添加的人',Icons.People,listTapped),
],
),
),
正文:ListView(
儿童:[
容器(
子:堆栈(
儿童:[
容器(
填充:来自LTRB(15.0,40.0,0.0,0.0)的边缘设置,
子:文本(
“添加人员”,
textAlign:textAlign.center,
样式:TextStyle(
字体大小:40.0,
颜色:Colors.teal,
fontWeight:fontWeight.bold,
fontFamily:“蒙特塞拉特”),
),
)
],
)),
容器(
填充:仅限边缘设置(顶部:35.0,左侧:20.0),
子:列(
儿童:[
_buildDateFIeld(),
升起的按钮(
按下时:()=>\u选择日期(上下文),
子:文本(
“选择日期”,
样式:TextStyle(fontFamily:“蒙特塞拉特”),
)),
_buildNameField(),
大小盒子(
身高:10.0,
),
_builPhoneField(),
大小盒子(
身高:25.0,
),
容器(
身高:40.0,
儿童:材料(
边界半径:边界半径。圆形(20.0),
shadowColor:Colors.greenAccent,
颜色:Colors.teal,
标高:7.0,
儿童:手势检测器(
onTap:(){},
儿童:中心(
子:文本(
“添加”,
样式:TextStyle(
颜色:颜色,白色,
fontFamily:“蒙特塞拉特”,
fontWeight:fontWeight.bold),
),
),
),
),
)
],
import 'package:flutter/material.dart';
import 'dart:async';

class Formscreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return FormscreenState();
  }
}

class FormscreenState extends State<Formscreen> {
  DateTime _selectedDate = DateTime.now();

  Widget _buildDateFIeld() {
    return Container(
      padding: const EdgeInsets.all(10),
      child: Center(
        child: Row(
          children: <Widget>[
            Expanded(
                child: Column(
              children: <Widget>[
                Text(
                  "When did you meet this person?",
                  style: TextStyle(fontSize: 16, fontFamily: 'Montserrat'),
                ),
              ],
            ))
          ],
        ),
      ),
    );
  }

  Widget _buildNameField() {
    return TextField(
      decoration: InputDecoration(
          icon: Icon(Icons.person),
          labelText: 'Name',
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.bold,
              color: Colors.grey)),
    );
  }

  Widget _builPhoneField() {
    return TextField(
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
          icon: Icon(Icons.phone),
          labelText: 'Phone Number',
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.bold,
              color: Colors.grey)),
    );
  }

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != _selectedDate)
      setState(() {
        _selectedDate = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(
            child: Text(
              "Track Acquintances",
              style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'Montserrat',
                  fontWeight: FontWeight.bold),
            ),
          ),
        ),
        drawer: Drawer(
          child: ListView(
            children: <Widget>[
              DrawerHeader(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: <Color>[Colors.teal, Colors.tealAccent])),
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Material(
                        elevation: 10,
                        borderRadius: BorderRadius.all(Radius.circular(50.0)),
                        child: Image.asset('images/corona.JPG',
                            width: 100, height: 100),
                      )
                    ],
                  ),
                ),
              ),
              CustomListTile('Add Person', Icons.add, addTapped),
              CustomListTile('View added People', Icons.people, listTapped),
            ],
          ),
        ),
        body: ListView(
          children: <Widget>[
            Container(
                child: Stack(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(15.0, 40.0, 0.0, 0.0),
                  child: Text(
                    'Add Person',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: 40.0,
                        color: Colors.teal,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Montserrat'),
                  ),
                )
              ],
            )),
            Container(
              padding: EdgeInsets.only(top: 35.0, left: 20.0),
              child: Column(
                children: <Widget>[
                  _buildDateFIeld(),
                  RaisedButton(
                      onPressed: () => _selectDate(context),
                      child: Text(
                        'Select date',
                        style: TextStyle(fontFamily: 'Montserrat'),
                      )),
                  _buildNameField(),
                  SizedBox(
                    height: 10.0,
                  ),
                  _builPhoneField(),
                  SizedBox(
                    height: 25.0,
                  ),
                  Container(
                    height: 40.0,
                    child: Material(
                      borderRadius: BorderRadius.circular(20.0),
                      shadowColor: Colors.greenAccent,
                      color: Colors.teal,
                      elevation: 7.0,
                      child: GestureDetector(
                        onTap: () {},
                        child: Center(
                          child: Text(
                            'Add',
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Montserrat',
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ));
  }
}

addTapped() {
  print("addTapped");
}

listTapped(BuildContext context) async {
  print("listTapped");
  //Navigator.of(context).pop();
  await Navigator.of(context)
      .push(MaterialPageRoute(builder: (context) => ListPerson()));
  Navigator.of(context).pop();
}

class CustomListTile extends StatelessWidget {
  final String _name;
  final IconData _icon;
  final Function onTap;

  CustomListTile(this._name, this._icon, this.onTap);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: EdgeInsets.fromLTRB(9, 0, 9, 0),
        child: Container(
          decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Colors.grey))),
          child: InkWell(
              splashColor: Colors.teal,
              onTap: () => onTap(context),
              child: Container(
                height: 50,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Icon(_icon),
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            _name,
                            style: TextStyle(
                                fontSize: 16, fontFamily: 'Montserrat'),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              )),
        ));
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Formscreen(),
    );
  }
}

class ListPerson extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("List Person"),
        ),
        body: Text("ListPerson"));
  }
}