解散小部件后导航到新页面将引发异常

时间:2019-01-06 10:08:28

标签: dart flutter

我在我的应用程序中有一个项目的ListView,并且该列表中的每个项目都包装在Dismissible小部件中,以便使滑动能够删除功能。我也有一个FloatingActionButton,按下时我导航到一个新页面。所有涉及滑动以关闭的功能都可以正常工作,但是如果我在关闭某个项目后按下浮动操作按钮,则会引发异常,并显示以下消息:

I/flutter (23062): A dismissed Dismissible widget is still part of the tree.
I/flutter (23062): Make sure to implement the onDismissed handler and to immediately remove the Dismissible
I/flutter (23062): widget from the application once that handler has fired.

代码如下:

Widget build(BuildContext context) {
    final String testVal = widget.testStr;
    return Scaffold(
        appBar: AppBar(
          title: Text('My Device Info'),
        ),
        body: FutureBuilder<AndroidDeviceInfo>(
          future: _deviceInfoPlugin.androidInfo,
          builder: (BuildContext context, AsyncSnapshot<AndroidDeviceInfo> snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              final androidDeviceInfo = snapshot.data;

              return ListView(
                children: <Widget>[
                  Dismissible(
                    key: Key('1'),
                    background: Container(color: Colors.red,),
                    onDismissed: (direction){

                    },
                    child: ListTile(
                      leading: Icon(Icons.info),
                      title: Text('Android build version: ${androidDeviceInfo.version.release}',
                        style: TextStyle(fontSize: 18.0),),
                    ),
                  ),

                  ListTile(
                      leading: Icon(Icons.info),
                      title: Text('Android device: ${androidDeviceInfo.device}',
                        style: TextStyle(fontSize: 18.0),),
                  ),
                  ListTile(
                      leading: Icon(Icons.info),
                      title: Text('Android device hardware: ${androidDeviceInfo.hardware}', style: TextStyle(fontSize: 18.0),),
                    )
                ],
              );
            }
          },
        ),
      floatingActionButton: FloatingActionButton(
          onPressed: (){
            Navigator.of(context).push(MaterialPageRoute(builder: (context){ return new AboutPage();}));
          },
        child: Icon(Icons.add),
      ),
    );
  }

如何避免引发此异常?我在这里做错什么了吗?

1 个答案:

答案 0 :(得分:0)

Key初始化为Dismissable的方式是错误的,因为Flutter认为可以有更多具有相同键值的Dismissable小部件。

uuid: ^1.0.3添加到您的依赖项中,

Dismissible(
  key: Key(Uuid().v4().toString()), //use the uuid.
    .
    .
    .