我知道有很多帖子在堆栈溢出方面有相同的错误,我已经浏览了很多,但我只是不明白其中的任何一个。感谢任何帮助/指导
所以,在我的 main.dart 文件中:
import 'package:flutter/material.dart';
import 'package:flutter_calendar/screens/wrapper.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_calendar/services/auth.dart';
import 'package:provider/provider.dart';
import 'package:flutter_calendar/models/myuser.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:flutter_calendar/event.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
initializeDateFormatting().then((_) => runApp(MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamProvider<MyUser?>.value(
child: MaterialApp(
home: Wrapper(),
theme: ThemeData(
primaryColor: Colors.deepPurple[400],
accentColor: Colors.deepPurple[50],
),
),
initialData: null,
value: AuthService().user,
);
}
}
这是我的 wrapper.dart 文件,我认为这是错误的来源:
class Wrapper extends StatelessWidget {
const Wrapper({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final user = Provider.of<MyUser>(context);
print(user);
//return home widget or authenticate widget
return Authenticate();
}
}
这是我的 auth.dart 文件:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_calendar/models/myuser.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Create MyUser object based on User
MyUser? _userfromFirebase(User user) {
return user != null ? MyUser(uid: user.uid) : null;
}
// auth change user stream
Stream<MyUser?> get user {
return _auth
.authStateChanges()
.map((User? user) => _userfromFirebase(user!));
}
// Sign in anonymously
Future signInAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
return _userfromFirebase(user!);
} catch (e) {
print(e.toString());
return null;
}
}
}
我已经尝试过:ProviderNotFoundException was thrown 所以我将我的 main.dart 文件更改为:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamProvider<MyUser?>(
create: (_) => AuthService(),
child: MaterialApp(
home: Wrapper(),
theme: ThemeData(
primaryColor: Colors.deepPurple[400],
accentColor: Colors.deepPurple[50],
),
),
initialData: null,
);
}
我已经通读了这个:Could not find the correct Provider - Flutter,但我认为它是不同的,因为我使用的是流提供程序,并且在文档上它说“尝试使用流来替换 ChangeNotifier 超出了此类的范围。 ”所以我没有尝试。我是 flutter/dart 的新手,正在学习旧教程,我已经能够解决很多问题,但现在我被卡住了!这是我关注的视频,如果它有帮助的话:https://www.youtube.com/watch?v=j_SJ7XmT2MM&list=PL4cUxeGkcC9j--TKIdkb3ISfRbJeJYQwC&index=9