找不到正确的提供者

时间:2020-09-20 07:54:30

标签: flutter dart flutter-dependencies flutter-provider

im试图使用Auth提供者作为自闭症。 我首先尝试使用常规ChangeNotifierProvider,但它不起作用。 然后我使用MultiProvider,它仍然无法正常工作。 我在互联网上阅读任何内容,但无济于事。 有谁知道如何解决? 我检查了所有进口,一切都很好。 而且我还有另一个应用程序使用了相同的技术,并且一切正常。.

import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';

import './screens/main_screen.dart';
import './screens/auth_screen.dart';
import './providers/Auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => Auth(),
        ),
      ],
      child: Consumer<Auth>(
        builder: (ctx, auth, child) => MaterialApp(
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: [
            Locale("he", "IR"),
          ],
          locale: Locale("he", "IR"),
          debugShowCheckedModeBanner: false,
          title: 'Loyalty Punch Card For Stores',
          theme: ThemeData(
            primaryColor: Color.fromRGBO(4, 30, 80, 1),
            accentColor: Color.fromRGBO(175, 234, 220, 1),
          ),
          home: auth.isAuth ? MainScreen() : AuthScreen(),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

像这样修改main()方法

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]).then((_) {
    runApp(MyApp());
  });
}

WidgetsFlutterBinding.ensureInitialized()如果需要在调用[runApp]之前初始化绑定,则需要调用此方法。

为什么不起作用:

因为setPreferredOrientations与异步执行任务的本机代码交互,所以使用ensureInitialized()来确保您拥有WidgetsBinding的实例。

更多参考: https://api.flutter.dev/flutter/widgets/WidgetsFlutterBinding/ensureInitialized.html