最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Show Error Recursive Function Navigator.push Flutter - Stack Overflow

programmeradmin5浏览0评论

I have a ListView.builder

That gets its data from

EnsaioItemModel ensaioitem = snapshot.data![index];

In the onTap: ()onTap: ()

I call the form to edit data

await Navigator.push(
  context,
  MaterialPageRoute(
  builder: (context) => EnsaioItemFormView(),
  ),
) 

In the form, I make the maintenance of data and close it with

Navigator.pop(_buildContext);

I need to close the form, get the next index of ListView, and call dethe form again.

So I call a recursive function in the onTab();

onTap: () => _chamaformulario(
  _buildContext,
  snapshot,
  index,
),

void _chamaformulario(
    BuildContext contextForm,
    AsyncSnapshot snapshot,
    int index,
  ) async {
    EnsaioItemModel ensaioitem = snapshot.data![index];

    final itemCount = snapshot.data.length;

    if (index >= itemCount) return;

    final ensaioitemSelecionado = EnsaioItemModel(
      ens_ite_codigo: ensaioitem.ens_ite_codigo,
      ens_codigo: ensaioitem.ens_codigo,
      gen_codigo: ensaioitem.gen_codigo,
      gen_nome: ensaioitem.gen_nome,
      ava_codigo: ensaioitem.ava_codigo,
      ens_ite_repeticao: ensaioitem.ens_ite_repeticao,
      ens_ite_estaca: ensaioitem.ens_ite_estaca,
      ens_ite_tratamento: ensaioitem.ens_ite_tratamento,
      ens_ite_ordem: ensaioitem.ens_ite_ordem,
      ens_ite_valor: ensaioitem.ens_ite_valor,
      ens_ite_avaliado_data: ensaioitem.ens_ite_avaliado_data,
      ens_ite_avaliado: ensaioitem.ens_ite_avaliado,
      ens_ite_enviado: ensaioitem.ens_ite_enviado,
    );
    _ensaioitemStore.inicializarFormulario(
      ensaioitem: ensaioitemSelecionado,
    );

    final result = await Navigator.push(
      contextForm,
      MaterialPageRoute(
        builder: (context) => EnsaioItemFormView(
            ens_codigo,
            ensaioitem.ens_ite_estaca,
            ensaioitem.ens_ite_tratamento,
            ensaioitem.gen_nome),
      ),
    );

    _ensaioitemStore.reinicilizarFormulario();

    index++;

    _chamaformulario(
      contextForm,
      snapshot,
      index,
    );
}

In the first time I call the function it´s works, but when go to call again in the line

final result = await Navigator.push(

Show error

Exception has occurred.
FlutterError (Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)

What's the problem?

I have a ListView.builder

That gets its data from

EnsaioItemModel ensaioitem = snapshot.data![index];

In the onTap: ()onTap: ()

I call the form to edit data

await Navigator.push(
  context,
  MaterialPageRoute(
  builder: (context) => EnsaioItemFormView(),
  ),
) 

In the form, I make the maintenance of data and close it with

Navigator.pop(_buildContext);

I need to close the form, get the next index of ListView, and call dethe form again.

So I call a recursive function in the onTab();

onTap: () => _chamaformulario(
  _buildContext,
  snapshot,
  index,
),

void _chamaformulario(
    BuildContext contextForm,
    AsyncSnapshot snapshot,
    int index,
  ) async {
    EnsaioItemModel ensaioitem = snapshot.data![index];

    final itemCount = snapshot.data.length;

    if (index >= itemCount) return;

    final ensaioitemSelecionado = EnsaioItemModel(
      ens_ite_codigo: ensaioitem.ens_ite_codigo,
      ens_codigo: ensaioitem.ens_codigo,
      gen_codigo: ensaioitem.gen_codigo,
      gen_nome: ensaioitem.gen_nome,
      ava_codigo: ensaioitem.ava_codigo,
      ens_ite_repeticao: ensaioitem.ens_ite_repeticao,
      ens_ite_estaca: ensaioitem.ens_ite_estaca,
      ens_ite_tratamento: ensaioitem.ens_ite_tratamento,
      ens_ite_ordem: ensaioitem.ens_ite_ordem,
      ens_ite_valor: ensaioitem.ens_ite_valor,
      ens_ite_avaliado_data: ensaioitem.ens_ite_avaliado_data,
      ens_ite_avaliado: ensaioitem.ens_ite_avaliado,
      ens_ite_enviado: ensaioitem.ens_ite_enviado,
    );
    _ensaioitemStore.inicializarFormulario(
      ensaioitem: ensaioitemSelecionado,
    );

    final result = await Navigator.push(
      contextForm,
      MaterialPageRoute(
        builder: (context) => EnsaioItemFormView(
            ens_codigo,
            ensaioitem.ens_ite_estaca,
            ensaioitem.ens_ite_tratamento,
            ensaioitem.gen_nome),
      ),
    );

    _ensaioitemStore.reinicilizarFormulario();

    index++;

    _chamaformulario(
      contextForm,
      snapshot,
      index,
    );
}

In the first time I call the function it´s works, but when go to call again in the line

final result = await Navigator.push(

Show error

Exception has occurred.
FlutterError (Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)

What's the problem?

Share Improve this question edited Mar 27 at 13:48 Frank van Puffelen 600k85 gold badges890 silver badges860 bronze badges asked Mar 27 at 13:27 MateusMateus 11 bronze badge
Add a comment  | 

2 Answers 2

Reset to default 0

While I am unsure on how to integrate it into your use case, here is a minimal example for an app which opens one form after the other. It does this by awaiting for navigator.push to return, which happens as soon as Form is popped.

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: Home()));

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future<void> _openForms() async {
    final items = ['a', 'b', 'c'];
    for (final item in items) {
      // Check if the widget is still mounted before attempting navigation
      if (!mounted) return;

      await Navigator.of(
        context,
      ).push(MaterialPageRoute(builder: (_) => FormPage(item: item)));

      // waits a bit before opening the next form
      if (!mounted) return;
      await Future.delayed(const Duration(milliseconds: 200));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: _openForms,
          child: const Text('Open Form'),
        ),
      ),
    );
  }
}

class FormPage extends StatelessWidget {
  final String item;

  const FormPage({super.key, required this.item});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Form for $item')),
      body: Center(
        child: ElevatedButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Submit'),
        ),
      ),
    );
  }
}

I created a function and call in the buildSuggestions

Widget buildSuggestions(BuildContext context) {
    _buildContext = context;

    executeAfterBuild();

In the function I call a Future.delayed because Flutter needed time for contruct the context again

Future<void> executeAfterBuild() async {
    if (retornoglobal == true) {
      Future.delayed(const Duration(milliseconds: 500), () {
        // this code will get executed after the build method
        // because of the way async functions are scheduled
        _chamaformulario(
          snapshotglobal,
          indexglobal,
        );
      });
    }
  }

It´s Worked

发布评论

评论列表(0)

  1. 暂无评论