小部件的生命周期问题

Issues with the lifecycle of a widget

我有一个 MaterialPageRoute 列表,我通过 GridView.count () 为每条路线挂载。当我从其中一个 MaterialPageRoute 移动并返回并重复相同的操作时发生故障,它抛出一个异常:

**════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
'package:flutter/src/widgets/navigator.dart': Failed assertion: line 4523 pos 12: 'entry.route._navigator == null': is not true.**

This is my GridView:

    GridView menuGrid(BuildContext context, List<MaterialPageRoute> lista,
        int columnas, int border) {
      return GridView.count(
        crossAxisCount: columnas,
        padding: const EdgeInsets.all(20),
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        children: <Widget>[
          ..._listado(context, lista, border),
        ],
      );
    }

这是列表:

List<Widget> _listado(
    BuildContext context, List<MaterialPageRoute> lista) {
  List<Widget> _listaWidget = [];
  lista.forEach((element) {
    _listaWidget.add(GestureDetector(
      onTap: () {
        Navigator.push(context, element);
      },
      child: Container(
          padding: const EdgeInsets.all(5),
          child: Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: Image.asset('assets/images/image1.png').image,
                fit: BoxFit.cover,
              ),
              border: Border.all(
                color: Colors.white,
                width: 2,
              ),
              borderRadius: new BorderRadius.only(
                topRight: const Radius.circular(20.0),
                bottomRight: const Radius.circular(20.0),
                topLeft: const Radius.circular(20.0),
                bottomLeft: const Radius.circular(20.0),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.white.withOpacity(0.5),
                  spreadRadius: 1,
                  blurRadius: 3,
                  offset: Offset(
                    4,
                    4,
                  ), // changes position of shadow
                ),
              ],
            ),
          )),
    ));
  });
  return _listaWidget;
}

列表例如:

List<MaterialPageRoute> lista= [
  MaterialPageRoute(builder: (_) => Page1()),
  MaterialPageRoute(builder: (_) => Page2()),
];

我找到了解决方案。我创建了一个摘要 class 来调用我的导航对象:

abstract class ElementoNavegacion {
  Image getImagen();
  MaterialPageRoute show();
}

class ElementoDatos extends ElementoNavegacion {
  Image getImagen() {
    return getImageWidget("datos");
  }

  MaterialPageRoute show() {
    return MaterialPageRoute(builder: (_) => DatosPage());
  }
}

然后我调用 -> Navigator.push(context, element[0].show()) 这是可行的,因为实例不会在内存中丢失。