1
votes

The complete error is as follows error is on line 2 Exception has occurred. FlutterError (ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. If you're running a test, you can call the TestWidgetsFlutterBinding.ensureInitialized() as the first line in your test's main() method to initialize the binding.)

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, "", "", "")));
            }
          }
        },
      ),
    );
  }
}
1

1 Answers

2
votes

The error message is already saying what you have to do in order to fix it, just use 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(),
  ));
}