【问题标题】:Navigation inside future method flutter未来方法中的导航颤动
【发布时间】:2020-08-03 04:49:09
【问题描述】:

我正在尝试从将来的方法导航到屏幕。但是我收到一个错误,说未定义的名称上下文。我尝试从 Widget build 导航,但参数是在此方法中创建的,我需要它来导航。我已经坚持了很长时间。任何帮助将不胜感激。

Future<void> addBookingConversation(Booking booking) async {
    Conversation conversation = Conversation();
    await conversation.addConversationToFirestore(booking.posting.host); //additional method working fine
    String text = "Hi, my name is ${AppConstants.currentUser.firstName}";
    await conversation.addMessageToFirestore(text); //additional method working fine
    //this is where i should navigate to the conversation page and facing the error here
    Navigator.push(
      context, //error here context undefined
      MaterialPageRoute(builder:
          (context) => ConversationPage(conversation: conversation,),
      ),
    );
  }
class ConversationPage extends StatefulWidget {

  final Conversation conversation;

  static final String routeName = '/conversationPageRoute';

  ConversationPage({this.conversation, Key key}) : super(key: key);

  @override
  _ConversationPageState createState() => _ConversationPageState();
}

class _ConversationPageState extends State<ConversationPage> {

  Conversation _conversation;
  // additional code of wiget build
  }

【问题讨论】:

  • 把你的addBookingConversation函数放在Widget build(BuildContext context)下面,其中context是定义的。

标签: flutter dart flutter-navigation


【解决方案1】:

我不知道你的函数在哪里,所以这是一些一般性的建议:

如果您无法访问方法中的变量,您有两种选择:将其作为参数从调用者传入。或者将结果返回给调用者,以便他们自己完成需要变量的部分。

这对您的方案意味着什么:您需要 context 作为方法中的附加参数,或者您需要从方法中返回 Future&lt;Conversation&gt; 并处理调用它的导航。

就我个人而言,我更喜欢第二种选择,因为您开始对话的业务逻辑和应用内导航是两个不同的问题,不应在一种方法中混为一谈。

【讨论】:

  • 我设法通过添加上下文的附加参数来修复它。谢谢你:)
【解决方案2】:

如果您想在应用程序的任何位置调用导航器方法。

class NavigationService {
  final GlobalKey<NavigatorState> globalKey = GlobalKey<NavigatorState>();

  Future<dynamic> navigateTo(Route Route) {   
  return globalKey.currentState.push(Route);
  }
}

在 main.dart 中。

 navigatorKey: NavigationService().globalKey,

然后在应用程序中的任何位置。 就用这个

Future<void> addBookingConversation(Booking booking) async {
Conversation conversation = Conversation();
await conversation.addConversationToFirestore(booking.posting.host); 
//additional method working fine
String text = "Hi, my name is ${AppConstants.currentUser.firstName}";
await conversation.addMessageToFirestore(text); //additional method working 
fine
//this is where i should navigate to the conversation page and facing the 
error here
NavigationService().navigateTo(
MaterialPageRoute(builder:
      (context) => ConversationPage(conversation: conversation,),
  ),);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2020-09-20
    • 2023-03-03
    • 2021-09-14
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多