Как я могу использовать Provider.of <T>(context) после пакета провайдера 4.0.0 во Flutter? - PullRequest
0 голосов
/ 09 июля 2020

Пытался изучить это приложение Flutter cra sh после преобразования потока Provider 3 в 4 , но я не смог реализовать.

context.read<T>() // Provider.of<T>(context, listen: false)
context.watch<T>() // Provider.of<T>(context)

, которые нужно изменить в моем случае.

    class LandingPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final _userModel = Provider.of<UserModel>(context);
        if (_userModel.state == ViewState.Idle) {
          if (_userModel.user == null) {
            return SignInPage();
          }else{
            return HomePage(user: _userModel.user);
          }
        } else {
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
      }
    }

Main.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "",
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: ChangeNotifierProvider(
          create: (context) => UserModel(),
          child: LandingPage()),
    );
  }
}

UserModel

enum ViewState { Idle, Busy }

class UserModel with ChangeNotifier implements AuthBase {
  ViewState _state = ViewState.Idle;
  UserRepository _userRepository = locator<UserRepository>();
  User _user;

  User get user => _user;

  ViewState get state => _state;

  set state(ViewState value) {
    _state = value;
    notifyListeners();
  }
  UserModel(){
    currentUser();
  }
@override
  Future<bool> signOut() async {
    try {
      state = ViewState.Busy;
      bool sonuc = await _userRepository.signOut();
      _user = null;
      return sonuc;
    } catch (e) {
      debugPrint("Viewmodeldeki current userda hata" + e.toString());
      return false;
    } finally {
      state = ViewState.Idle;
    }
  }
}

В моем приложении я много раз использую этот «final _userModel = Provider.of (context ); " чтобы получить доступ к классу UserModel. После нового пакета провайдера он выдает мне эту ошибку. Когда я заменил "Provider.of (context, listen: false);" в моих кодах я не могу обновить свой пользовательский интерфейс.

  debugIsInInheritedProviderUpdate': Tried to listen to a value exposed with 
provider, from outside of the widget tree.
     This is likely caused by an event handler (like a button's onPressed) that called
     Provider.of without passing `listen: false`.
     To fix, write:
     Provider.of<UserModel>(context, listen: false);
...