【问题标题】:FlutterError (ServicesBinding.defaultBinaryMessenger was accessed before the binding was initializedFlutterError(在初始化绑定之前访问了ServicesBinding.defaultBinaryMessenger
【发布时间】:2020-09-07 13:09:48
【问题描述】:

完整的错误如下error is on line 2 发生异常。 FlutterError(在初始化绑定之前访问了ServicesBinding.defaultBinaryMessenger。 如果您正在运行一个应用程序并且需要在调用runApp() 之前访问二进制信使(例如,在插件初始化期间),那么您需要首先显式调用WidgetsFlutterBinding.ensureInitialized()。 如果你正在运行一个测试,你可以调用TestWidgetsFlutterBinding.ensureInitialized()作为你测试的main()方法的第一行来初始化绑定。)

void main() async {
  final FirebaseStorage storage = await initStorage(STORAGE_BUCKET);
  final FirebaseStorage autoMlStorage = await initStorage(AUTOML_BUCKET);

  runApp(new MyApp(
    storage: storage,
    autoMlStorage: autoMlStorage,
    userModel: UserModel(),
  ));
}

enum MainAction { logout, viewTutorial }

class MyApp extends StatelessWidget {
  final FirebaseStorage storage;
  final FirebaseStorage autoMlStorage;
  final UserModel userModel;

  const MyApp({
    Key key,
    @required this.storage,
    @required this.autoMlStorage,
    @required this.userModel,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScopedModel<UserModel>(
      model: userModel,
      child: new InheritedStorage(
        storage: storage,
        autoMlStorage: autoMlStorage,
        child: new MaterialApp(
          title: 'Custom Image Classifier',
          theme: new ThemeData(
            primaryColor: Colors.white,
            accentColor: Colors.deepPurple,
            dividerColor: Colors.black12,
          ),
          initialRoute: MyHomePage.routeName,
          routes: {
            MyHomePage.routeName: (context) => MyHomePage(),
            IntroTutorial.routeName: (context) => IntroTutorial(),
          },
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  static const routeName = '/';

  const MyHomePage();

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

  void checkAndShowTutorial() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final seenTutorial = prefs.getBool('seenTutorial') ?? false;
    if (!seenTutorial) {
      Navigator.pushNamed(context, IntroTutorial.routeName);
    } else {
      print("Has seen tutorial before. Skipping");
    }
  }

  @override
  Widget build(BuildContext context) {
    final model = ScopedModel.of<UserModel>(context, rebuildOnChange: true);
    final query = Firestore.instance.collection('datasets');

    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: new Text("Datasets"),
        actions: <Widget>[
          if (!model.isLoggedIn())
            IconButton(
              onPressed: () {
                model
                    .beginSignIn()
                    .then((user) => model.setLoggedInUser(user))
                    .catchError((e) => print(e));
              },
              icon: Icon(
                Icons.person_outline,
              ),
            ),
          model.isLoggedIn()
              ? PopupMenuButton<MainAction>(
                  onSelected: (MainAction action) {
                    switch (action) {
                      case MainAction.logout:
                        model.logOut();
                        break;
                      case MainAction.viewTutorial:
                        Navigator.pushNamed(context, IntroTutorial.routeName);
                        break;
                    }
                  },
                  itemBuilder: (BuildContext context) =>
                      <PopupMenuItem<MainAction>>[
                    PopupMenuItem<MainAction>(
                      child: Text.rich(
                        TextSpan(
                          text: 'Logout',
                          children: [
                            TextSpan(
                              text: " (${model.user.displayName})",
                              style: TextStyle(
                                color: Colors.black38,
                                fontStyle: FontStyle.italic,
                              ),
                            )
                          ],
                        ),
                      ),
                      value: MainAction.logout,
                    ),
                    const PopupMenuItem<MainAction>(
                      child: Text('View Tutorial'),
                      value: MainAction.viewTutorial,
                    )
                  ],
                )
              : Container()
        ],
      ),
      body: DatasetsList(
        scaffoldKey: _scaffoldKey,
        query: model.isLoggedIn()
            ? query
            : query.where('isPublic', isEqualTo: true),
        model: model,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      // show fab button only on personal datasets page
      floatingActionButton: new FloatingActionButton.extended(
        icon: Icon(Icons.add),
        label: Text("New Dataset"),
        onPressed: () async {
          if (model.isLoggedIn()) {
            Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      AddDatasetLabelScreen(DataKind.Dataset, "", "", ""),
                ));
          } else {
            // Route to login page
            final result = await Navigator.push(
                context, MaterialPageRoute(builder: (context) => SignInPage()));
            if (result) {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          AddDatasetLabelScreen(DataKind.Dataset, "", "", "")));
            }
          }
        },
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    错误消息已经说明了你必须做什么才能修复它,只需使用WidgetsFlutterBinding.ensureInitialized()

    
    void main() async {
      await WidgetsFlutterBinding.ensureInitialized();
      final FirebaseStorage storage = await initStorage(STORAGE_BUCKET);
      final FirebaseStorage autoMlStorage = await initStorage(AUTOML_BUCKET);
    
      runApp(MyApp(
        storage: storage,
        autoMlStorage: autoMlStorage,
        userModel: UserModel(),
      ));
    }
    

    【讨论】:

    • 您不需要使用new,如果这能解决您的问题,请不要忘记投票并接受。
    猜你喜欢
    • 2020-04-11
    • 2020-11-22
    • 2020-01-01
    • 2020-12-29
    • 2021-09-10
    • 2020-10-23
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多