![](/img/trans.png)
[英]Calling a void function in main.dart from another dart file
[英]Calling a function from another dart file
我有一個包含大量代碼的主頁,我想在另一個 dart 文件中分離用於構建 TextInput 填充對話框的代碼,並在 HomePage 上下文中調用該 function。
//DialogBox code
import 'package:flutter/material.dart';
Future<String> _shareDialogBox(BuildContext context) async {
String shareContent = '';
return showDialog<String>(
context: context,
barrierDismissible:
false, // dialog is dismissible with a tap on the barrier
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter current team'),
content: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
autofocus: true,
decoration: InputDecoration(
//prefixIcon: Icon(Icons.note_add),
//icon: Icon(Icons.note_add),
hintText: 'Add Description',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
borderSide: BorderSide(color: Colors.grey),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
borderSide: BorderSide(color: Colors.grey),
),
),
onChanged: (value) {
shareContent = value;
},
))
],
),
actions: <Widget>[
FlatButton(
child: Text('Share on Facebook'),
onPressed: () {
Navigator.of(context).pop(shareContent);
},
),
FlatButton(
child: Text('Share on Twitter'),
onPressed: () {
Navigator.of(context).pop(shareContent);
},
)
],
);
},
);
}
現在我已經在文件 DialogBox.dart 中編寫了這段代碼
我想在我的 Homepage.dart 在 onTap() 事件上按這樣的方式調用_shareDialogBox()
function。
import 'package:app_name/ui_components/ShareDialogBox.dart';
GestureDetector(
onTap: () async {
await _shareDialogBox(context);
},
child: Row(
children: <Widget>[
Icon(
Icons.reply,
size: 15,
color: Colors.black54,
),
SizedBox(width: 5),
Text("Share",
style: TextStyle(
fontSize: 14.0,
color: Colors.black54)),
],
)
),
我收到錯誤消息
error: The method '_shareDialogBox' isn't defined for the class '_MyHomePageState'. (undefined_method at ---- lib/HomePage.dart:308)
有人可以幫助理解為什么會這樣。
除了使用下划線外,看起來是正確的。 這使它成為私有方法/變量。
並且只能在同一個文件中使用。 (或其以part of 'library'
開頭的文件
只需從_shareDialogBox
重命名為shareDialogBox
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.