Maxim Vershinin
Maxim Vershinin

Reputation: 643

How to use data from Provider during initState in Flutter application

I am refactoring my Flutter application code by adding Provider as a state management.

Desired behavior: When Home screen opens, app should check if users email verified, if it's not then should show dialog popup.

Problem: It worked fine when I was passing data for EmailVerified through the constructor, but if I want to use Provider, I can't get this data at initState() lifecycle.

Can you please recommend me correct approach for such use case?

import 'package:myapp/services/authentication.dart';
import 'package:myapp/screens/settings_screen.dart';
import 'package:flutter/material.dart';
import 'package:myapp/services/authentication.dart';
import 'package:provider/provider.dart';

class HomeScreen extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => new _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  bool _isEmailVerified = false;

  @override
  void initState() {
    super.initState();
    _checkEmailVerification(); // <=== Method which should show Dialog box if email is not verified which is coming from "Auth" Provider
  }

  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<Auth>(context, listen: false); // <==== Service from Provider, which contains data for _isEmailVerified
    auth.isEmailVerified().then((value) => _isEmailVerified = value);

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('My App'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text(
              'Welcome to my app',
            ),
          ],
        ),
      ),
    );
  }

  void _checkEmailVerification() async {
    _isEmailVerified = auth.isEmailVerified(); // <=== How can I use "auth" from Provider to get isEmailVerified data ????
    if (!_isEmailVerified) {
      _showVerifyEmailDialog();
    }
  }

  void _showVerifyEmailDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Verify your account"),
          content: new Text("Please verify account in the link sent to email"),
          actions: <Widget>[
            new FlatButton(
              child: new Text("Resend link"),
              onPressed: () {
                Navigator.of(context).pop();
                _resentVerifyEmail();
              },
            ),
            new FlatButton(
              child: new Text("Dismiss"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void _resentVerifyEmail() {
    // Logic to send email
  }
}

Upvotes: 41

Views: 56330

Answers (8)

Karthik
Karthik

Reputation: 27

Adding a MultiProvider in main file fixed it

runApp( MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserDataNotifier()),
      ],
      child: MyApp(),
    ),););

Upvotes: 0

Ramazan Burak Ekinci
Ramazan Burak Ekinci

Reputation: 61

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

  Future.microtask(() {
      final MapsProvider mapsProvider = context.read<MapsProvider>();
    });
  }

Upvotes: 2

Nikhith sunil
Nikhith sunil

Reputation: 285

You can make your initState as follows:

@override
void initState() {
    super.initState();
    final myModel = Provider.of<YourProivder>(context, listen: false);
}

Upvotes: 7

Karamat Subhani
Karamat Subhani

Reputation: 272

For this, we need to bindwidget. so provider give us this feature too

 WidgetsBinding.instance.addPostFrameCallback((_) {
      auth = Provider.of<Auth>(context, listen: false);
     _isEmailVerified = auth.isEmailVerified()

    });

Upvotes: -1

oblomov
oblomov

Reputation: 544

You can also pass context to HomeScreen widget, which will let you access Provider :

class HomeScreen extends StatefulWidget {
  final BuildContext context;
  HomeScreen(this.context);

  @override
  State<StatefulWidget> createState() => new _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool _isEmailVerified = false;

  void _checkEmailVerification() async {
    _isEmailVerified = widget.context.read<Auth>().isEmailVerified();
    if (!_isEmailVerified) {
      _showVerifyEmailDialog();
    }
  }

...

}

Upvotes: 0

Sebastian
Sebastian

Reputation: 3894

You need to use the context to call Provider.of() so you can add addPostFrameCallback() which is called after the first build, there you can use the context

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

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      auth = Provider.of<Auth>(context, listen: false);
    });
}

Upvotes: 93

Jhoan River
Jhoan River

Reputation: 86

In version 3.0.0+1,you can also do

you can do it with

var CallNotifier auth;


@override
void initState(){
 super.initState();
 auth = Provider.of<CallNotifier>(context, listen = false);
}

Upvotes: -6

Vinoth
Vinoth

Reputation: 9764

From Provider v4.1.0, you can also use read() method. It reduces the boilerplate code.

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

  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    auth = context.read<Auth>();
  });
}

Upvotes: 14

Related Questions