flutter 生成使用者时引发ProviderNotFoundException

yvfmudvl  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(219)

我在Flutter应用程序中有以下类:

class SubTemasScreen extends StatefulWidget {
  const SubTemasScreen({Key? key}) : super(key: key);

  @override
  State<SubTemasScreen> createState() => _SubTemasScreenState();
}

class _SubTemasScreenState extends State<SubTemasScreen> {
  final TextEditingController _controller = TextEditingController();

  Timer? timer;

  bool verTodos = true;
  bool verActivos = false;
  bool verNoActivos = false;
  bool verAdmin = false;
  bool verCosmicos = false;
  bool verMecenas = false;
  bool verVerificados = false;
  bool verNoVerificados = false;

  void initTimer() {
    if (timer != null && timer!.isActive) return;

    timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      //job
      setState(() {});
    });
  }

  bool _esActivo = true;
  String miEmail = "";

  Future getData() async {
    var url = Constantes().urlAPI + "get_datos_usuario.php";

    http.Response response = await http.get(Uri.parse(url));
    List data = json.decode(response.body);

    User? usuarioActual = FirebaseAuth.instance.currentUser;

    if (usuarioActual != null) {
      miEmail = usuarioActual.email!;
      print("miEmail es ${miEmail}");
      for (var i = 0; i < data.length; i++) {
        String s = data![i]["email"];
        if (s == miEmail) {
          var activo = data![i]["activo"];
          print("activo ${activo}");

          if (activo == "1") {
            _esActivo = true;
          } else {
            _esActivo = false;
          }
        }
      }
    }
  }

  @override
  void initState() {
    super.initState();

    getEmailUsuarioActual();
    initTimer();
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  getEmailUsuarioActual() {
    getData();
  }

  //EVITAR BACK BUTTON

  Future<bool> _onWillPop() async {
    return false; //<-- SEE HERE
  }

  @override
  Widget build(BuildContext context) {
    var filtrado = "0";

    return _esActivo
        ? WillPopScope(
            onWillPop: _onWillPop,
            child: SafeArea(
              child: Scaffold(
                body: Consumer<TemasProvider>(
                    builder: (context, proveedor, _) {
                  return Column(
                    children: [
                      FilaSuperiorPantallas(),
                      SizedBox(
                        height: 15,
                      ),
                      BuscadorTextField(
                        controller: _controller,
                        hintText: "Buscar sub-temas por título",
                      ),

                      SizedBox(
                        height: 8,
                      ),
                      //lista de temas para filtrar subtemas
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Text("Selecciona un tema para filtrar"),
                          filtrado != "0"
                              ? IconButton(
                                  onPressed: () {},
                                  icon: Icon(
                                    Icons.filter_alt_off_outlined,
                                    size: 23,
                                  ))
                              : IconButton(
                                  onPressed: () {},
                                  icon: Icon(
                                    Icons.filter_alt,
                                    size: 23,
                                  ))
                        ],
                      ),
                      ListaTemasHorizontalLight(),

                      //LISTA DE sub TEMAS TODOS
                      ListaSubtemasTodos(controller: _controller)
                    ],
                  );
                }),
              ),
            ),
          )
        : NoActivo();
  }

  Future<Null> refresh() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {});
  }
}

我在第行得到以下异常:

body: Consumer<TemasProvider>(
                    builder: (context, proveedor, _) {

我在widgets树的顶部声明了TemasProvider:

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'MYSTERYMAP ADMIN',
      theme: ThemeData(
        primarySwatch: Colors.grey,
      ),
      home: MultiProvider(providers: [
        ChangeNotifierProvider(create: (_) => AutenticacionProvider()),
        ChangeNotifierProvider(create: (_) => TemasProvider()),
      ], child: WidgetTree()),
    );
  }
}

这是异常输出:

======== Exception caught by widgets library =======================================================
The following ProviderNotFoundException was thrown building Consumer<TemasProvider>:
Error: Could not find the correct Provider<TemasProvider> above this Consumer<TemasProvider> Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that Consumer<TemasProvider> is under your MultiProvider/Provider<TemasProvider>.
  This usually happens when you are creating a provider and trying to read it immediately.

编辑
这里是TemasProvider类:
import 'package:flutter/material. dart';

class TemasProvider extends ChangeNotifier {

 String temaActual= "0";

  void cambiarTemaActualState(String s) {

    temaActual = s;
    notifyListeners();
  }

}
igetnqfo

igetnqfo1#

如果您希望您的提供程序在小部件树中的任何地方都可用(在所有屏幕上),您应该在MaterialApp小部件上方提供它。因此,在您的情况下,您应该像这样将MaterialApp小部件与MultiProvider Package 在一起:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => AutenticacionProvider()),
        ChangeNotifierProvider(create: (_) => TemasProvider()),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'MYSTERYMAP ADMIN',
        theme: ThemeData(
          primarySwatch: Colors.grey,
        ),
        home: WidgetTree(),
      ),
    );
  }
}

相关问题