Ошибка: не удалось найти правильный поставщик <ApiService>над этим виджетом LoginPage - PullRequest
0 голосов
/ 06 мая 2020

Привет, я пытаюсь вызвать POST api с помощью chopper. но он дает мне

«Ошибка: не удалось найти правильный поставщик над этим виджетом LoginPage».

Даже если я добавил поставщика в качестве виджета-предка на страницу.

Что я делаю не так? пожалуйста помоги.

 @override
 Widget build(BuildContext context) {
return Provider(
  create: (_) => ApiService.create(),
  dispose: (context, ApiService service) => service.client.dispose(),
  child: Container(
                          width: double.infinity,
                          child: ButtonTheme(
                            height: 36.0,
                            child: RaisedButton(
                              onPressed: () async {
                                //Navigator.pushReplacementNamed(context, "/myjourney");
                                print("Arpit: ${_emailController.text + " " +_passwordController.text}");
                                generateMd5(_passwordController.text);
                                String email = _emailController.text;
                                String password = generateMd5(_passwordController.text);
                                 final response = await Provider.of<ApiService>(context)
                                  .doLogin("d1d2fe0514f7d5c748c0e7e085b36f74",email,password,"App");
                              print(response.body);
                              },
                              color: Colors.white,
                              disabledColor: Colors.white,
                              shape: BeveledRectangleBorder(),
                              textColor: Colors.indigo,
                              padding: EdgeInsets.all(8.0),
                              splashColor: Color(0xFF6c60e4),
                              child: Text("SIGN IN", style: TextStyle(
                                  fontFamily: "Montserrat",
                                  fontSize: 15.0,
                                  color: Colors.indigo,fontWeight: FontWeight.bold)),
                            ),
                          )
                      ),
);

}

Ответы [ 2 ]

1 голос
/ 06 мая 2020

Вы получаете сообщение об ошибке, потому что вы не помещаете Provider над Login Page, который в нем нуждается.

Вы должны поместить любой Provider, который вы используете, над любым виджетом, который его использует . Этот процесс называется Lifting state up.

Чтобы исправить ошибку, удалите виджет Provider из виджета Login и заключите его в виджет root вашего приложения.

Как код ниже:

void main() {
  runApp(
    Provider(
    create: (_) => ApiService.create(),
    dispose: (context, ApiService service) => service.client.dispose(),      
    child: MyApp(),
    ),
  );
}

Чтобы узнать больше о состоянии подъема вверх. Проверьте ссылку ниже:

Правильное использование провайдера

Надеюсь, это поможет.

0 голосов
/ 06 мая 2020

вы можете использовать Consumer ниже, чтобы избежать использования неправильного контекста:

@override
Widget build(BuildContext context) {
  return Provider(
    create: (_) => Foo(),
    child: Consumer<Foo>(
      builder: (_, foo, __) => Text(foo.value),
    },
  );
}

Вот так:

@override
 Widget build(BuildContext context) {
return Provider<ApiService>(
  create: (_) => ApiService.create(),
  dispose: (context, ApiService service) => service.client.dispose(),
  child: Consumer<ApiService>(
          builder: (_, apiService, __) => Container(
                          width: double.infinity,
                          child: ButtonTheme(
                            height: 36.0,
                            child: RaisedButton(
                              onPressed: () async {
                                //Navigator.pushReplacementNamed(context, "/myjourney");
                                print("Arpit: ${_emailController.text + " " +_passwordController.text}");
                                generateMd5(_passwordController.text);
                                String email = _emailController.text;
                                String password = generateMd5(_passwordController.text);
                                 final response = await apiService.doLogin("d1d2fe0514f7d5c748c0e7e085b36f74",email,password,"App");
                              print(response.body);
                              },
                              color: Colors.white,
                              disabledColor: Colors.white,
                              shape: BeveledRectangleBorder(),
                              textColor: Colors.indigo,
                              padding: EdgeInsets.all(8.0),
                              splashColor: Color(0xFF6c60e4),
                              child: Text("SIGN IN", style: TextStyle(
                                  fontFamily: "Montserrat",
                                  fontSize: 15.0,
                                  color: Colors.indigo,fontWeight: FontWeight.bold)),
                            ),
                          )
                      ),
);

Проверьте документацию COnsumer здесь: https://pub.dev/documentation/provider/latest/provider/Consumer-class.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...