19

I'm trying to implement Provider and it seems it works fine but I get this message:

This _DefaultInheritedProviderScope widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: _DefaultInheritedProviderScope value: Instance of 'UserProfile' listening to value The widget which was currently being built when the offending call was made was: FutureBuilder dirty state: _FutureBuilderState#bf6ec When the exception was thrown, this was the stack:

0 Element.markNeedsBuild. (package:flutter/src/widgets/framework.dart:3896:11)

1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:3911:6)

2 _InheritedProviderScopeMixin.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:268:5)

3 ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:206:21)

4 UserProfile.user= (package:mdd/core/services/user_info.dart:13:5) ... The UserProfile

sending notification was: Instance of 'UserProfile'

My code is the following:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final authService = Provider.of<AuthService>(context);
    final userProfile =    Provider.of<UserProfile>(context);

    return StatefulWrapper(
      onInit: () {
        FirebaseNotifications().setUpFirebase();
      },
      child: FutureBuilder<User>(
        future: authService.getUser(),
        builder: (context, AsyncSnapshot<User> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.error != null) {
              return Text(snapshot.error.toString());
            }
            userProfile.user = snapshot.data;
           // FirebaseUser user = snapshot.data;

            return snapshot.hasData ? ListScreen() : LoginScreen();
          } else {
            return Scaffold(
              appBar: AppBar(),
              body: Container(),
            );
          }
        },
      )
    );
  }
}

And this is the UserProfile class:

class UserProfile with ChangeNotifier {
  User _user = User();

  get user {
    return _user;
  }

  set user(User user) {
    this._user = user;
    notifyListeners();
  }
}

and the part of the AuthService used to fetch the profile:

Future<User> getUser() async {
  print('GETTING THE USER');
  final fbaseUser = await _auth.currentUser();
  final snapshot = await _db.collection('users')
      .document(fbaseUser.uid)
      .get();
  if (snapshot.data != null) {
    Map<dynamic, dynamic> jsres = snapshot.data;
    _user = User.fromJson(jsres);
    return _user;
  }
}

Why am I getting this error? What am I doing wrong? Can anyone help me with this, please?

John Smith Optional
  • 431
  • 2
  • 4
  • 18

6 Answers6

14

You can copy paste run full code below, full code fix this issue
Reason:
This line userProfile.user = snapshot.data; cause error
FutureBuilder is build data, and receive notifyListeners()

From Flutter team's suggestion, https://github.com/flutter/flutter/issues/16218#issuecomment-403995076
The FutureBuilder's builder should only build widgets, it shouldn't have any logic. Builders can get called arbitrarily.

Solution:
In user case, after getUser() you can directly set UserProfile.user
Step 1: remove final userProfile = Provider.of<UserProfile>(context);
Step 2: move userProfile.user = snapshot.data; logic to futureBuilder's future

FutureBuilder<User>(
          future: _future.then((value) =>
              Provider.of<UserProfile>(context, listen: false).user = value),

full code

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => UserProfile(),
      child: MyApp(),
    ),
  );
}

class StatefulWrapper extends StatefulWidget {
  final Function onInit;
  final Widget child;
  const StatefulWrapper({@required this.onInit, @required this.child});
  @override
  _StatefulWrapperState createState() => _StatefulWrapperState();
}

class _StatefulWrapperState extends State<StatefulWrapper> {
  @override
  void initState() {
    if (widget.onInit != null) {
      widget.onInit();
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

class User {
  String name;

  User({this.name});
}

Future<User> getUser() async {
  print("getUser");
  return User(name: "test");
}

class UserProfile with ChangeNotifier {
  User _user = User();

  get user {
    return _user;
  }

  set user(User user) {
    this._user = user;
    notifyListeners();
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //final authService = Provider.of<AuthService>(context);
    //final userProfile = Provider.of<UserProfile>(context, listen: false);
    Future _future = getUser();

    return StatefulWrapper(
        onInit: () {
          //FirebaseNotifications().setUpFirebase();
        },
        child: FutureBuilder<User>(
          future: _future.then((value) =>
              Provider.of<UserProfile>(context, listen: false).user = value),
          builder: (context, AsyncSnapshot<User> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.error != null) {
                return Text(snapshot.error.toString());
              }


              if (snapshot.hasData) {
                return ListScreen();
              } else {
                return LoginScreen();
              }
            } else {
              return Scaffold(
                appBar: AppBar(),
                body: Container(),
              );
            }
          },
        ));
  }
}

class ListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("ListScreen");
  }
}

class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("LoginScreen");
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}
chunhunghan
  • 51,087
  • 5
  • 102
  • 120
  • Thank you! So there's no problem to maintain the final authService = Provider.of(context); and use it to to be able to use authService.getUser function in the future parameter I suppose. I mean, that's the way I did it and it works, but just to be sure it's a goof practice. – John Smith Optional Mar 26 '20 at 11:13
  • If you encounter FutureBuilder rebuilds unnecessarily, you can reference this https://github.com/flutter/flutter/issues/11426#issuecomment-414047398 – chunhunghan Mar 27 '20 at 00:52
8

I have also face the same issue while updating the state with the help of notifylisteners().

Solution:-

WidgetsBinding.instance?.addPostFrameCallback((_) {
  notifyListeners();
});
Sanju Bhatt
  • 944
  • 10
  • 7
4

code with problem:

if(condition)
{
  ...
  ...
  notifyListners(); // problem
}else{
  await Future....
  ...
  ...
  notifyListners();  //not getting problem here    
}

code with solution: i am not using await thats why getting the error. so use await in async function, before using notifyListners()

if(condition)
{
  ...
  ...
  await Future.delayed(Duration(milliseconds: 1)); // use await 
  notifyListners(); 
}else{
  await Future....
  ...
  ...
  notifyListners();      
}
Yash Zade
  • 163
  • 1
  • 4
  • The delay/sleep seems arbitrary. The value could change based on client/server load. While this may work in some scenarios, this does not seem to be the right solution. – banerjk Aug 19 '22 at 06:33
2

When I got this message it turned out that there was a notifylisteners() call in a widget that was a listener.

I just removed the superfluous notifyListeners() call and everything worked.

YEG
  • 473
  • 4
  • 12
1

Before

class UserProfile with ChangeNotifier {
  User _user = User();

  get user {
    return _user;
  }

  set user(User user) {
    this._user = user;
    notifyListeners();
  }
}

Add one more method:

  void Adduser(User user) {
    this._user = user;
  }

Now notifier model class:

class UserProfile with ChangeNotifier {
  User _user = User();

  get user {
    return _user;
  }

  set user(User user) {
    this._user = user;
    notifyListeners();
  }

  void Adduser(User user) {
    this._user = user;
  }
}

Call:

userProfile.Adduser(snapshot.data);

Problem:

///problem is here and notifylistner
userProfile.user = snapshot.data;

Whenever we call notifylistner() rebuild the widget.

zeed
  • 285
  • 1
  • 5
  • 18
lava
  • 6,020
  • 2
  • 31
  • 28
1

In case someone is calling the method from initState() in which the notifyListeners() is called, then you will also get this error. The solution is below

  @override
  void initState() {
    
    
    Future.delayed(Duration.zero).then((value) {
     Provider.of<'//'>(context, listen: false).callMethod();
    });

    super.initState();
  }
Adil Shinwari
  • 408
  • 2
  • 10