这是我的第二堂课
class SecondClass extends StatefulWidget {
_SecondClassState createState() => _SecondClassState();
}
class _SecondClassState extends State<SecondClass> {
@override
Widget build(BuildContext context) {
Return Container(
RaisedButton(
onPressed: Navigator.of(context).pop('lorem ipsum),
child: Text('Back and get data')
)
);
}
}
这是我的第一堂课
class FirstClass extends StatefulWidget {
_FirstClassState createState() => _FirstClassState();
}
class _FirstClassState extends State<FirstClass> {
@override
Widget build(BuildContext context) {
Return Container(
// show data here
);
}
}
如何获取lorem ipsum
的字符串并将其显示在第一课中,我应该在其中放置获取该字符串的代码?
答案 0 :(得分:1)
您可以在屏幕快照中看到,在第二个屏幕中单击的任何项目,它将发送回第1页,并且Button显示相同的项目。
这是基本实现的完整代码。
void main() {
runApp(MaterialApp(home: Page1()));
}
class Page1 extends StatefulWidget {
@override
_Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {
String _response = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 1")),
body: Center(
child: RaisedButton(
child: Text("Go to Page 2"),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => Page2())).then((value) {
setState(() {
_response = value; // you receive here
});
});
},
),
),
);
}
}
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 2")),
body: ListView.builder(
itemCount: 20,
itemBuilder: (c, i) {
return ListTile(
title: Text("Item ${i}"),
onTap: () {
Navigator.pop(context, "Item ${i}"); // what you pass here
},
);
},
),
);
}
}
答案 1 :(得分:0)
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondClass())).then((value) {
// value is lorem ipsum
});
导航到FirstClass
时,应在SecondClass
中使用它。
完整解决方案:
class _FirstClassState extends State<FirstClass> {
String _string = "";
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text("Go"),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondClass())).then(
(value) {
setState(() {
_string = value; // lorem ipsum
});
},
);
},
);
}
}