当我专注于TextField-Bloc Pattern时,小部件重新渲染 [英] Widget re-render when I focus on a TextField - Bloc Pattern

查看:60
本文介绍了当我专注于TextField-Bloc Pattern时,小部件重新渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用BLoC来保持两个嵌套FullScreenDialogs之间的状态.

I'm using a BLoC to keep state between two nested FullScreenDialogs.

按下第一个屏幕时,我正在初始化bloc,

I'm initializing the bloc when I push the first screen, like so

return FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () {
        Navigator.of(context).push(MaterialPageRoute(
          builder: (BuildContext context) => ProductBlocProvider(child: ProductEntryScreen()),
          fullscreenDialog: true
        ));
      },
    );

ProductEntryScreen具有一堆TextFields和一个按钮,可以打开一个新的FullScreenDialog.此新屏幕还具有TextFields. 我遇到的问题是,每当我在第二个FullScreenDialog上的TextField上书写时,启动ProductBlocProvider的onPressed函数都会再次运行.

ProductEntryScreen has a bunch of TextFields and a button than opens a new FullScreenDialog. This new Screen also has TextFields. The problem I'm having is that every time I write on a TextField on the second FullScreenDialog, the onPressed function where I start the ProductBlocProvider runs again.

重新运行导致Bloc创建一个新实例,所以我最终失去了状态.

And that re-run is causing the Bloc to create a new instance, so I end up loosing the state.

我想做什么? 也许我做错了,所以我将解释我要实现的目标.

What I want to do? Maybe I'm doing it wrong so I'll explain what I'm trying to achieve.

在填充所有字段时,我想保持两个FullScreenDialogs之间的状态,完成后,我想按一个按钮,将所有数据(两个屏幕)发送到数据库.

I want to keep state between the two FullScreenDialogs while I fill all the fields, and when I'm done I want to press a button that send all of the data (both screens) to a database.

推荐答案

问题是我在MaterialPageRoute的builder函数中的提供程序内部创建了bloc的实例.

The problem is that I was creating the instance of the bloc inside the provider in the builder function of the MaterialPageRoute.

该构建器函数被反复调用,并每次都创建一个新的bloc实例.解决方案是从builde函数中删除bloc实例的创建,如下所示:

That builder function was being called repeatedly, and creating a new instance of the bloc every time. The solution was to take out from the builde function the creation of the bloc instance, like this:

return FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () {
        //Here I create the instance
        var _bloc = ProductBloc();
        Navigator.of(context).push(MaterialPageRoute(
          //And I pass the bloc instance to the provider
          builder: (BuildContext context) => ProductBlocProvider(bloc: _bloc, child: ProductEntryScreen()),
          fullscreenDialog: true
        ));
      },
    );

这篇关于当我专注于TextField-Bloc Pattern时,小部件重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆