I retrieve the logged in user's Name based upon the uid from a stream called UserData. With this stream I can put the users name on the dashboard title. Ex. "Tom's Dashboard'.
I'm using stream builder in the dashboard page (below) to retrieve the name, but I receive the "getter 'uid' null" on logout because, I'm guessing, stream builder rebuilds.
Therefore, how else can I retrieve the name without using Stream Builder? I tried using "Provider.of(context)", but I also get an error about the stream being on another route.
Dashboard Page:
class Dashboard extends StatefulWidget {
final Function toggleView;
Dashboard({this.toggleView});
@override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String currName;
String title;
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder(
key: _formKey,
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
UserData userData = snapshot.data;
currName = userData.name;
if (currName == 'new member') {
title = 'Dashboard';
} else {
title = currName; //+ "'s Dashboard";
}
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('$title'),
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.person),
label: Text(''),
onPressed: () async {
Navigator.pushNamed(context, '/');
await _auth.signOut();
},
),
FlatButton.icon(
icon: Icon(Icons.settings),
label: Text(''),
onPressed: () => _showSettingsPanel(),
),
],
),
);
});
}
}
UserData stream:
UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
return UserData(
uid: uid,
name: snapshot.data['name'],
location: snapshot.data['location'],
accountType: snapshot.data['accountType']);
}
Stream<UserData> get userData {
return userProfileCollection
.document(uid)
.snapshots()
.map(_userDataFromSnapshot);
}
}
main.dart:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return StreamProvider<User>.value(value: AuthService().user,
child: MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
//home: Login(),
initialRoute: '/',
routes: {
'/': (context) => AuthLoading(),
'/home': (context) => Login(),
'/register': (context) => Register(),
'/dashboard': (context) => Dashboard(),
},
));
}
}