如何在flutter中的几个类之间使用提供者beet?

时间:2019-12-28 23:27:56

标签: flutter

我正在扑朔迷离地创建一个注册应用程序,但是使用单个屏幕显示的信息太多,所以我决定在屏幕中使用选项卡视图,并将屏幕分成抽屉对象。

但是我需要使用来自不同屏幕的信息来保存它。所以我考虑使用Multiprovider。但是当我尝试使用提供程序中的信息时,它会抛出:

Could not find the correct Provider<General> above this Baseformularios Widget

我的实现是这样的:

这是我的抽屉,上面有第一个字段General,这是有关客户的基本信息, 如您所见,提供程序是在此处创建的,并且body:是由称为bodycontent的变量提供的,当尝试更改表单时,它将被覆盖,但是当我尝试打印用户名时,它将在上面抛出错误。

MultiProvider(
      providers: [
        ChangeNotifierProvider<General>(
          create: (context)=>General(),
        )
      ],
      child: Scaffold(
        appBar: AppBar(
          title: Text("Historias clinicas"),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.check),
              onPressed: (){
                print(Provider.of<General>(context).nombre);
              Provider.of<General>(context).addCLiente();
              },
            )
          ],
        ),
        body: bodycontent,
        drawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              AspectRatio(
                aspectRatio: 0.001/0.001,
                child:  DrawerHeader(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(colors: [Colors.white,Colors.blueAccent]
                  ),
                ),
              ),

              ListTile(
                title: Text("General"),
                onTap: (){
                  setState(() {
                    bodycontent = I_II_III_IV();
                  });
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      ),
    );

这是常规形式的用法:

Provider.of<General>(context).set(nombre.text,
        "Apellido hay que quitar en la funcion",
        edad.text,
        _currentsexo,
        estado_civil.text,
        direccion.text,
        emergencia.text,
        procedencia.text,
        telefono.text,
        ocupacion.text,
        referencia.text,
        fecha_inicio.text,
        "",userid);

这样可以很好地保存信息,我在调试器中检查了一下,但是问题出在另一端。

我尝试在带有抽屉的屏幕之前在屏幕中使用multiprovider,但是它抛出了相同的错误,但带有“通用形式以上”。请注意,尝试此操作时,我已从抽屉中的屏幕上删除了Multiprovider。

所以我应该在每个屏幕中声明多提供程序以将其用作其子吗?因为我以为是那个提供程序,您可以在声明屏幕的每个屏幕之后在每个屏幕上使用变量,否则我会误会某些内容?...非常感谢您的帮助,

1 个答案:

答案 0 :(得分:1)

要从应用程序的每个位置访问提供程序,应在主窗口中声明它:

void main()  {
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider<General>(
        create: (context) => General(),
      ),
    ],
    child: MyApp(),
  ));
}

希望有帮助。 致敬。