我如何将数据从一个小部件传递到另一个小部件。 我正在从Firebase获取数据,并且希望在小部件之间传递数据。 我不能做到这一点。
例如,为此,我正在从此小部件中获取数据
class _SettingState extends State<Setting> {
final AuthService _auth = AuthService();
@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 Column(
children: <Widget>[
Container(
child: Text('working)
)
]
);
}
});
}
}
现在我想将数据传递到此小部件
class Inbox extends StatefulWidget {
@override
_InboxState createState() => _InboxState();
}
class _InboxState extends State<Inbox> {
final AuthService _auth = AuthService();
@override
Widget build(BuildContext context) {
return Center(
child: Text('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)
您可以将参数添加到Inbox
小部件,并以如下状态使用它:
class Inbox extends StatefulWidget {
final UserData userData;
Inbox({Key key, this.userData}): super(key: key);
@override
_InboxState createState() => _InboxState();
}
class _InboxState extends State<Inbox> {
final AuthService _auth = AuthService();
@override
Widget build(BuildContext context) {
return Center(
child: Text(widget.userData.username),
),
);
}
}
答案 1 :(得分:0)
您可以使用参数将数据发送到新屏幕。
相同的文档为here
-----拥有数据的屏幕--------
ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
// When a user taps the ListTile, navigate to the DetailScreen.
// Notice that you're not only creating a DetailScreen, you're
// also passing the current todo to it.
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(todo: todos[index]),
),
);
},
);
},
);
-----需要传递数据的屏幕------
class DetailScreen extends StatelessWidget {
// Declare a field that holds the Todo.
final Todo todo;
// In the constructor, require a Todo.
DetailScreen({Key key, @required this.todo}) : super(key: key);
@override
Widget build(BuildContext context) {
// Use the Todo to create the UI.
return Scaffold(
appBar: AppBar(
title: Text(todo.title),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(todo.description),
),
);
}
}
快乐编码!!!