我想将数据从一个小部件传递到另一个小部件。 我正在从Firebase获取数据,并且希望在小部件之间传递数据。 如何将数据从一个屏幕传递到另一屏幕。 这就是我的代码。
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentindex = 0;
final List<Widget> _children = [
Dashboard(),
Search(),
];
void onTappedBar(int index) {
setState(() {
_currentindex = index;
});
}
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder<UserData>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
UserData userData = snapshot.data;
return return Scaffold(
backgroundColor: Color(0xFFf6f5fb),
body: _children[_currentindex],
bottomNavigationBar: CurvedNavigationBar(
onTap: onTappedBar,
index: _currentindex,
items: <Widget>[
Icon(
Icons.home,
),
Icon(
Icons.search,
],
),
);
});
}
}
从此小部件中,数据从firebase加载。现在,我想将 snapshot.data 传递给Dashboard()
小部件和Search()
小部件。
我想显示用户名Dashboard()。 这就是我的```Dashboard()``小部件的例子
class Dashboard extends StatefulWidget {
@override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Here i want display the data')
),
);
}
}
这是模型类:
class User {
final String uid;
User({this.uid});
}
class UserData {
final String uid;
final String username;
final String phonenumber;
UserData({ this.uid, this.username, this.phonenumber });
}
答案 0 :(得分:0)
如果是像您这样的简单情况,则将其传递给构造函数:
class Dashboard extends StatefulWidget {
final UserData userData;
// userData is not optional-named parameter
const Dashboard(this.userData, {Key key}) : super(key: key);
@override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
@override
Widget build(BuildContext context) {
final UserData userData = widget.userData;//do something with user
return Center(
child: Text('user is ${user.username}')
),
);
}
}
和HomeState
(不要将小部件另存为类的字段,而是动态创建它们):
class _HomeState extends State<Home> {
int _currentindex = 0;
void onTappedBar(int index) {
setState(() {
_currentindex = index;
});
}
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder<UserData>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
UserData userData = snapshot.data;
return Scaffold(
backgroundColor: Color(0xFFf6f5fb),
body: Column(
children: [
Dashboard(userData),
Search(userData),
],
),
bottomNavigationBar: CurvedNavigationBar(
onTap: onTappedBar,
index: _currentindex,
items: <Widget>[
Icon(
Icons.home,
),
Icon(
Icons.search,
],
),
);
});
}
}