如何将非字符串数据传递到Flutter中的命名路由?

时间:2017-11-21 18:11:22

标签: dart flutter

我有很多屏幕,我正在使用Navigator。我想使用“命名路由”,但我还需要将非字符串(例如图像)传递给我的下一个路径。

我无法使用pushNamed(),因为我无法将非字符串数据传递给它。

如何使用命名路由+发送非字符串数据?

10 个答案:

答案 0 :(得分:39)

修改

现在可以将复杂的参数传递给Navigator.pushNamed

String id;
Navigator.pushNamed(context, '/users', arguments: id);

然后可以在onGenerateRoute内使用它来使用这些参数自定义路由构建:

MaterialApp(
  title: 'Flutter Hooks Gallery',
  onGenerateRoute: (settings) {
    final arguments = settings.arguments;
    switch (settings.name) {
      case '/users':
        if (arguments is String) {
          // the details page for one specific user
          return UserDetails(arguments);
        }
        else {
          // a route showing the list of all users
          return UserList();
        }
      default:
        return null;
    }
  },
);

答案 1 :(得分:3)

这里有许多巨大的解决方案,但是使用此库,您的问题可以用两行代码解决: https://pub.dev/packages/get

List users = [2,4,6,3]
Get.toNamed('/second', arguments: users);

在第二条路线上

print(Get.arguments);
// out: [2,4,6,3]

与其他解决方案相比,使用它的优点是您可以通过参数传递任何内容,甚至可以通过类实例传递参数,并且可以从用户界面以及您的用户组,控制器,提供者和等等,而不必将onGenerateRoute中的参数传递给该类。

答案 2 :(得分:2)

Flutter Cookbook显示了如何导航到新页面 并将非字符串数据传递给它。

target socket's id

我从Navigator.pushedNamed()开始,因为它很简单并且没有任何数据可传递。当我的需求发生变化并且想要传递数据时,我切换到Navigator.push()

示例:

var nextPageData = {foo:'bar'};

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => 
     MyNextPage(myData: nextPageData))
 );

答案 3 :(得分:2)

使用onGenerateRoute可以很容易地在Navigator.pushNamedNavigator.pushReplacementNamed的路由转换中传递复杂的参数

显示概念的最小设置是

main.dart

import 'package:flutter/material.dart';
import 'package:navigator/routes.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Navigation Demo',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      onGenerateRoute: (RouteSettings settings) {
        return MaterialPageRoute(
          builder: (BuildContext context) => makeRoute(
                context: context,
                routeName: settings.name,
                arguments: settings.arguments,
              ),
          maintainState: true,
          fullscreenDialog: false,
        );
      },
    );
  }
}

routes.dart

_buildRoute方法中,我们检查路由名称并将参数强制转换为所需的类型。

一个缺点是,如果必需的参数不是简单类型,则必须事先定义类型。

import 'package:flutter/material.dart';

import 'package:navigator/list.dart';
import 'package:navigator/details.dart';

Widget makeRoute(
    {@required BuildContext context,
    @required String routeName,
    Object arguments}) {
  final Widget child =
      _buildRoute(context: context, routeName: routeName, arguments: arguments);
  return child;
}

Widget _buildRoute({
  @required BuildContext context,
  @required String routeName,
  Object arguments,
}) {
  switch (routeName) {
    case '/':
      return ArticleList();
    case '/ArticleView':
      Article article = arguments as Article;
      return ArticleView(article: article);
    default:
      throw 'Route $routeName is not defined';
  }
}

观看次数

list.dart

使用已定义的类型Article构造route参数。

import 'package:flutter/material.dart';
import 'package:navigator/details.dart' show Article;

class ArticleList extends StatefulWidget {
  @override
  _ArticleListState createState() => _ArticleListState();
}

class _ArticleListState extends State<ArticleList> {
  List<Article> articles = [
    Article(
        id: 1,
        title: 'Article 1',
        author_name: 'Nilotpal',
        summary: 'Article 1 summary'),
    Article(
        id: 2,
        title: 'Article 2',
        author_name: 'Mike',
        summary: 'Article 2 summary'),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Articles'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            ListTile(
              title: Text('${articles[0].title}'),
              subtitle: Text('by ${articles[0].author_name}'),
              onTap: () {
                Navigator.of(context)
                    .pushNamed('/ArticleView', arguments: articles[0]);
              },
            ),
            ListTile(
              title: Text('${articles[1].title}'),
              subtitle: Text('by ${articles[1].author_name}'),
              onTap: () {
                Navigator.of(context)
                    .pushNamed('/ArticleView', arguments: articles[1]);
              },
            ),
          ],
        ),
      ),
    );
  }
}

details.dart

定义参数类型

import 'package:flutter/material.dart';

class Article {
  final int id;
  final String author_name;
  final String title;
  final String summary;

  Article(
      {@required this.id,
      @required this.author_name,
      @required this.title,
      @required this.summary});
}

class ArticleView extends StatelessWidget {
  final Article _article;

  ArticleView({@required Article article}) : _article = article;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${_article.title}'),
      ),
      body: SafeArea(
        top: true,
        child: Center(
          child: Column(
            children: <Widget>[
              Text('${_article.author_name}'),
              Text('${_article.summary}'),
            ],
          ),
        ),
      ),
    );
  }
}

答案 4 :(得分:1)

针对此问题的结果,我开发了软件包

链接:https://pub.dartlang.org/packages/navigate

可以满足您的期望并且易于使用

User

答案 5 :(得分:1)

您可以使用App的参数routes直接传递参数。

赞:

  routes: {
    HomePage.route: (_) => HomePage(),
    DetailsPage.route: (context) =>
        DetailsPage(ModalRoute.of(context).settings.arguments),
  },

在这种情况下,完整的示例将类似于下一个示例:

import 'package:flutter/material.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          initialRoute: HomePage.route,
          routes: {
            HomePage.route: (_) => HomePage(),
            DetailsPage.route: (context) =>
                DetailsPage(ModalRoute.of(context).settings.arguments),
          },
        );
      }
    }

    class HomePage extends StatelessWidget {
      static const String route = '/';

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              Navigator.pushNamed(context, '/details',
                  arguments: ScreenArguments(
                    'My Details',
                    'Some Message',
                  ));
            },
          ),
        );
      }
    }

    class DetailsPage extends StatelessWidget {
      static const String route = '/details';

      final ScreenArguments arguments;

      DetailsPage(this.arguments);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(arguments.title),
          ),
          body: Center(
            child: Text(arguments.message),
          ),
        );
      }
    }

    class ScreenArguments {
      final String title;
      final String message;

      ScreenArguments(this.title, this.message);
    }

答案 6 :(得分:0)

我正在用相机捕获图像,然后将其传递到确认页面,如下所示:

   ImagePicker.pickImage(source: source).then((File file) {
    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => MediaCaptured(file: file),
        ));
  });

您可以轻松地对任何类型的文件或非字符串数据执行相同的操作。

var foo = "non-string data";
Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => MediaCaptured(foo: foo),
        ));

通过路由的类名调用路由的下一页,如上所述。

只需确保您的新页面在其构造函数中接受此内容。

 // Stateful Widget
class MediaCaptured extends StatefulWidget {
    MediaCaptured({ Key key, @required this.foo,}) : super(key: key);
    final var foo;
}

// StatelessWidget
class MediaCaptured extends StatelessWidget {
    MediaCaptured(this.foo);
    var foo;
}

答案 7 :(得分:0)

使用地图

在推送参数时,您可以将其以地图形式推送,并且在提取参数时也可以这样做。

例如

同时推送

Navigator.of(context).pushNamed(
              'second',
              arguments: {
                'title':'This is a String',
                       or
                 'Fx': This could be any widget or Function
              }

提取目标页面中的参数

final routes=ModalRoute.of(context).settings.arguments as Map<String,String>;

    return Scaffold(
      appBar: AppBar(
              title: Text(routes['title']),
              ),
      body: Container(
        child: Center(
          child: RaisedButton(
            child: Text("Back"),
            onPressed: ()=>Navigator.of(context).pop(),
          ),
        ),
      ),
    );

and choose your map accordingly accordingly

答案 8 :(得分:0)

来自第一个 StateFul 类:

Navigator.of(context).pushNamed('/pending_order',arguments: {"staff" : staffObj});

到第二个 StateFul 类:

  class PendingOrders extends StatefulWidget {
  @override
  _PendingOrdersState createState() => _PendingOrdersState();
}

class _PendingOrdersState extends State<PendingOrders> {
  StaffModel staffModelObj;

  @override
  Widget build(BuildContext context) {
    final routes =
        ModalRoute.of(context).settings.arguments as Map<String, dynamic>;
    if (routes != null) {
      staffModelObj = routes["staff"];
    }
    return Scaffold(...);}}

答案 9 :(得分:-4)

We can pass any type of arguments when declaring routes as constructor arguments as below,

For example to send a list of Strings,

List<String> titles = [];

void main() => runApp(
      new MaterialApp(
        home: new FirstPage(),
        routes: <String, WidgetBuilder>{
          "/SecondPage": (BuildContext context) => new SecondPage(titles),
        },
      ),
    );

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new RaisedButton(onPressed: () {
        Navigator.of(context).pushNamed('/SecondPage');
      }),
    );
  }
}

class SecondPage extends StatelessWidget {
  final List<String> titles;

  SecondPage(this.titles);

  @override
  Widget build(BuildContext context) {
    return new ListView.builder(
      itemBuilder: (context, index) {
        return new ListTile(
          title: new Text(titles[index]),
        );
      },
    );
  }
}