如何使按钮在Flutter中打开随机页面? [英] How make button which open random page in Flutter?

查看:77
本文介绍了如何使按钮在Flutter中打开随机页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章,非常抱歉。我有一个问题,我无法创建一个按钮来打开我的apk中的随机页面。该项目与冠状病毒连接。

This is my first post, so sorry for errors. I have a problem I can't make a button which open radom page in my apk. The project is connected with Coronavirus.

推荐答案

您可以轻松地使用 RouteGenerator 并列出所需的随机页面

You can easily use RouteGenerator and list with needed random pages for this task.

main.dart:

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Random pages',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: 'start_page',
      onGenerateRoute: RouteGenerator.generateRoute,
    );
  }
}

route_generator.dart:

class RouteGenerator {

  static List<String> myRandomPages = [
    'first_page',
    'second_page'
  ];

  static String getRandomNameOfRoute(){
    return myRandomPages[Random().nextInt(myRandomPages.length)];
  }

  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {

      case 'start_page':
        return MaterialPageRoute(builder: (_) => StartPage());

      case 'first_page':
        return MaterialPageRoute(builder: (_) => FirstPage()); // FirstPage - is just a Widget with your content

      case 'second_page':
        return MaterialPageRoute(builder: (_) => SecondPage());// Also custom Widget

      //... other random or not pages

    }
  }

}

start_page.dart:

class StartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Start page'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('Go to random page'),
            onPressed: () => Navigator.of(context).pushNamed(RouteGenerator.getRandomNameOfRoute()),
          ),
        )
    );
  }
}

这篇关于如何使按钮在Flutter中打开随机页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆