java - 如何将按钮呈现到 main.dart 文件?另外,有没有什么方法可以在不使用任何按钮的按下()的情况下将参数传递给命名路由?
问题描述
这是 main.dart,目前参数在按钮的 press() 上传递,我请求建议一种方法(如果有)将参数从 main.dart(示例)传递到 plugin.dart,而不使用按钮!。
void main() {
runApp(new MaterialApp(
home: new MyApp(),
routes: {
ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
},
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My test app'),
),
body: Center(
child: Text('This example app'),
),
// A button that navigates to a named route. The named route extracts the arguments by itself.
floatingActionButton: FloatingActionButton(
child: Text("Boutton"), //button that is passing arguments to named route.
onPressed: () {
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Click me', //custom button name
'abc', //api key
),
);
},
)
);
}
}
下面是 plugin.dart 文件,我在其中发出 http 获取请求。我如何在 main.dart 中调用它,以便按钮以相同的方式呈现。
class ScreenArguments {
final String buttonName;
final String api;
ScreenArguments(this.buttonName, this.api);
}
class ExtractArgumentsScreen extends StatefulWidget {
_ExtractArgumentsScreen createState() => _ExtractArgumentsScreen();
static const routeName = '/extractArguments';
}
// A widget that extracts the necessary arguments from the ModalRoute.
class _ExtractArgumentsScreen extends State<ExtractArgumentsScreen> {
Future<String> myButton() async {
// Extract the arguments from the current ModalRoute settings and cast
// them as ScreenArguments.
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
String url = "example.com/project/details?key=" + args.api;
final response = await http.get(url);
// headers: {"Accept":"application/json"});
if (response.statusCode == 200) {
print(response.body);
return args.buttonName;
}
return null;
}
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: myButton(),
builder: (context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return FloatingActionButton( //this button has to be rendered to main.dart file
child: Text(snapshot.data),
onPressed: () {
MyForm();
},
);
} else {
return CircularProgressIndicator();
}
}
);
}
}
class MyForm extends State<ExtractArgumentsScreen> {
@override
Widget build(BuildContext context) {
// code for form widget
}
}
该方法在语法上是否正确?!
解决方案
推荐阅读
- asp.net-core - 在具有 EF Core 迁移的 Net Core 类库上使用 settings.json
- matlab - 如何在 MATLAB 中调整条形绝对宽度
- c++ - Qt 对于我的带宽上限来说太大了。我的替代方案是什么?
- uitableview - 设置 UITableViewCellAccessory 的左 X 位置
- dask - 无法通过 SSH 启动 dask 集群
- appium - 如何使用 Appium 运行需要两台设备的测试
- java - XWPFRun 生成运行并修剪空格
- java - 如何在 Android 中使用 google/api/annotations.proto
- material-ui - 无法缩小代码 ./node_modules/@material-ui/core/es/styles/createMuiTheme.js
- python - Django 模型中的日期数组