Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

dart - Flutter. Navigator.pushedNamed with argument

I am navigating to another widget like this, with an argument of a custom object:

  Navigator.pushNamed(context, '/mortgage_screen', arguments: {'mortgageModel': mortgageModel});

Now, according to the flutter docs, I can get the argument in the build method of the new widget, like this:

final MortgageModel args = ModalRoute.of(context)!.settings.arguments;

However, I am getting this error message:

A value of type 'Object?' can't be assigned to a variable of type 'MortgageModel'. Try changing the type of the variable, or casting the right-hand type to 'MortgageModel'.

Thanks

question from:https://stackoverflow.com/questions/65891858/flutter-navigator-pushednamed-with-argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Navigator.pushNamed(context, '/mortgage_screen', arguments: {'mortgageModel': mortgageModel});

Should be:

Navigator.pushNamed(context, '/mortgage_screen', arguments: mortgageModel),

Your code above is passing a Map<String,MortgageModel> type object, not a MortgageModel type object.

And I'm guessing this was a typo: ! (excalamation point) in your args assignment statement? I can't think of a reason why it would be there.

ModalRoute.of(context)!.settings.arguments;

Here's a complete example:

import 'package:flutter/material.dart';

class PassArgsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/': (context) => PageOne(),
        PageTwo.routeName: (context) => PageTwo()
      },
    );
  }
}

class MortgageModel {
  int yearsLeft = 30;
}

class PageOne extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    MortgageModel mortgageModel = MortgageModel();
    return Center(
      child: RaisedButton(
        child: Text('Go 2 /w Args'),
        onPressed: () => Navigator.pushNamed(context, PageTwo.routeName, arguments: mortgageModel),
      ),
    );
  }
}

class PageTwo extends StatelessWidget {
  static const routeName = '/pageTwo';
  @override
  Widget build(BuildContext context) {
    MortgageModel mortgageModel = ModalRoute.of(context).settings.arguments;
    return Scaffold(
      appBar: AppBar(title: Text('Pass Args P.2'),),
      body: Center(
        child: Text('Mortgage years remaining: ${mortgageModel.yearsLeft}'),
      ),
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...