简体   繁体   中英

Flutter/Dart Could not find correct Provider<> above this Widget

I am new to flutter and trying to create a "rating" page where users can select 1-5 stars and submit. I then want to add that to firestore along with the current user ID (whoever is logged in). Here is how I get my current user id:

  class AuthService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  bool isLoggedIn = false;

  Stream<String> get onAuthStateChanged =>
  _firebaseAuth.onAuthStateChanged.map((FirebaseUser user) => user?.uid);

  // GET UID
  Future<String> getCurrentUID() async {
  return (await _firebaseAuth.currentUser()).uid;
  }

I have then tried to integrate this into my ratings page:

import 'package:easy_tiger/constants/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:provider/provider.dart';
import 'package:easy_tiger/services/auth_service.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


  class RateUs extends StatefulWidget {
  @override
  _RateUsState createState() => _RateUsState();
}

class _RateUsState extends State<RateUs> {
  @override
  Widget build(BuildContext context) {
    String _currentUser = currentUser(context);
    double finalRating = 0;
    return Scaffold(
      appBar:
      AppBar(
        leading: GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Icon(Icons.arrow_back)),
        title: Text('Rate us'),),
      backgroundColor: Colors.white,
    body: Column(
      children: [
        FlutterRatingBar(
          initialRating: 5,
          fillColor: kPrimaryColor,
          borderColor: kPrimaryColor.withAlpha(50),
          onRatingUpdate: (double rating) {finalRating = rating ;},

        ),
        Center(
          child: RaisedButton(
            child: Text('Submit'),
              elevation: 8.0,
              onPressed: () =>
                  Firestore.instance.collection('ratings').document(_currentUser).setData({
                    'uID' : _currentUser,
                    'Rating' : finalRating,
                    'Submitted at' : DateTime.now()
                  })),
        ),
      ],
    ),);
  }
}

String currentUser (BuildContext context)  {
  final auth = Provider.of(context).auth;
  String currentUser =  auth.getCurrentUID();
  return currentUser;
}

But get the following error:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ProviderNotFoundError was thrown building RateUs(dirty, state: _RateUsState#ad8a3):
Error: Could not find the correct Provider<dynamic> above this RateUs Widget

How can I add the correct provider above the RateUs Widget?

Here. First of all extend your AuthService class to ChangeNotifier

  class AuthService extends ChangeNotifier {
    final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
    bool isLoggedIn = false;
  
    Stream<String> get onAuthStateChanged =>
        _firebaseAuth.onAuthStateChanged.map((FirebaseUser user) => user?.uid);
  
    // GET UID
    Future<String> getCurrentUID() async {
      return (await _firebaseAuth.currentUser()).uid;
    }

and also you just can't use Provider.of(context) you have to specify which provider class. Like Provider.of<AuthService>(context)

And before using Provider.of<AuthService>(context) you've to create the Provider class with ChangeNotifierProvider .

  ChangeNotifierProvider(
     create : (ctx) => AuthService(),
     child: YourWidget(),
  ),

then only you can use Provider.of<AuthService>(context) .

And make sure you use ChangeNotifierProvider in the top-level widget of the widget tree otherwise you will get the context not found Error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM