首页 > 解决方案 > Flutter:如何为每个项目导航到另一个屏幕

问题描述

我想为每个项目导航到另一个页面。我怎样才能做到这一点?

我有每个项目的 dart 文件(screen_one.dart、screen_two.dart 等)。如果它是一个容器,我可以进行导航,但为此我不知道如何为每个项目应用导航。

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int get color1 => null;

  int get color2 => null;


  @override
  Widget build(BuildContext context) {

                return Scaffold(
                  appBar: AppBar(
                    leading: IconButton(icon: Icon(Icons.menu), onPressed: () {

                    }),
                    //title: Text("Sample Stack"),
                    actions: <Widget>[
                      IconButton(icon: Icon(
                        FontAwesomeIcons.calendarAlt), onPressed: () {

                        }),
                    ],
                  ),
                  body:GridView.count(
                  crossAxisCount: 1,
                  padding: EdgeInsets.all(16.0),
                  childAspectRatio: 3.0,
                  crossAxisSpacing: 10.0,
                  mainAxisSpacing: 10.0,
                  children: <Widget>[
                    myGridItems("SAMPLE ONE", "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg", 0xFF02b5e0, 0xFF02cabd),
                    myGridItems("SAMPLE TWO", "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg", 0xFF02b5e0, 0xFF02cabd),
                    myGridItems("SAMPLE THREE", "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg", 0xFF02b5e0, 0xFF02cabd),
                    myGridItems("SAMPLE FOUR", "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg", 0xFF02b5e0, 0xFF02cabd),
                    myGridItems("SAMPLE FIVE", "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg", 0xFF02b5e0, 0xFF02cabd),
                    myGridItems("SAMPLE SIX", "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg", 0xFF02b5e0, 0xFF02cabd),
      ],
      ),
    );
  }

  Widget myGridItems(String gridName, String gridImage, int color1, int color2) {

    return Container(
       decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(24.0),
          gradient: new LinearGradient(
            colors: [
              Color(color1),
              Color(color2),
            ],
            begin: Alignment.centerLeft,
            end: new Alignment(1.0, 1.0),
            ),
      ), 
      child: Stack(
        children: <Widget>[
          Opacity(
          opacity: 0.3,
          child: Container(
            decoration: new BoxDecoration(
              borderRadius: BorderRadius.circular(24.0),
            image: DecorationImage(
              image: NetworkImage(
                gridImage),
              fit: BoxFit.fill,
              ),
            ),),
          ),

          Column(
            mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(child:Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(child:Text("Job", style: TextStyle(color: Colors.white, fontSize: 16),)),
                SizedBox(width: 10.0),
                  Container(child: Icon(FontAwesomeIcons.compass, color: Colors.white,)),
                  SizedBox(width: 10.0),
                  Container(child:Text("Guide",style: TextStyle(color: Colors.white, fontSize: 16),)),
              ],)),
              SizedBox(height: 10.0),
        Padding(
          padding: const EdgeInsets.only(left:16.0),
        child:Text(gridName,style: TextStyle(color: Colors.white,fontSize: 20, fontWeight: FontWeight.bold),)),
          ],)
        ],
      )
    );

标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
您可以在使用onGenerateRoutepushName使用gridName

代码片段

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    // Getting arguments passed in while calling Navigator.pushNamed
    final args = settings.arguments;
    print(settings.name);
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(builder: (_) => HomePage());
        break;
      case '/SAMPLE ONE':
        // Validation of correct data type
        if (args is String) {
          return MaterialPageRoute(
            builder: (_) => SampleOne(
              gridName: args,
            ),
          );
        }
        break;
      case '/SAMPLE TWO':
        if (args is String) {
          return MaterialPageRoute(
            builder: (_) =>
                SampleTwo(
                  gridName: args,
                ),
          );
        }
        // If args is not of the correct type, return an error page.
        // You can also throw an exception while in development.
        return _errorRoute();
      default:
        // If there is no such named route in the switch statement, e.g. /third
        return _errorRoute();
    }
  }
...
 initialRoute: '/',
      onGenerateRoute: RouteGenerator.generateRoute,
...
 Widget myGridItems(
      String gridName, String gridImage, int color1, int color2) {
    return InkWell(
      onTap: () {
        Navigator.of(context).pushNamed(
          '/$gridName',
          arguments: gridName,
        );
      },      

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() {
  runApp(MyApp());
}

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    // Getting arguments passed in while calling Navigator.pushNamed
    final args = settings.arguments;
    print(settings.name);
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(builder: (_) => HomePage());
        break;
      case '/SAMPLE ONE':
        // Validation of correct data type
        if (args is String) {
          return MaterialPageRoute(
            builder: (_) => SampleOne(
              gridName: args,
            ),
          );
        }
        break;
      case '/SAMPLE TWO':
        if (args is String) {
          return MaterialPageRoute(
            builder: (_) =>
                SampleTwo(
                  gridName: args,
                ),
          );
        }
        // If args is not of the correct type, return an error page.
        // You can also throw an exception while in development.
        return _errorRoute();
      default:
        // If there is no such named route in the switch statement, e.g. /third
        return _errorRoute();
    }
  }

  static Route<dynamic> _errorRoute() {
    return MaterialPageRoute(builder: (_) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Error'),
        ),
        body: Center(
          child: Text('ERROR'),
        ),
      );
    });
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: '/',
      onGenerateRoute: RouteGenerator.generateRoute,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int get color1 => null;

  int get color2 => null;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.menu), onPressed: () {}),
        //title: Text("Sample Stack"),
        actions: <Widget>[
          IconButton(
              icon: Icon(FontAwesomeIcons.calendarAlt), onPressed: () {}),
        ],
      ),
      body: GridView.count(
        crossAxisCount: 1,
        padding: EdgeInsets.all(16.0),
        childAspectRatio: 3.0,
        crossAxisSpacing: 10.0,
        mainAxisSpacing: 10.0,
        children: <Widget>[
          myGridItems(
              "SAMPLE ONE",
              "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg",
              0xFF02b5e0,
              0xFF02cabd),
          myGridItems(
              "SAMPLE TWO",
              "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg",
              0xFF02b5e0,
              0xFF02cabd),
          myGridItems(
              "SAMPLE THREE",
              "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg",
              0xFF02b5e0,
              0xFF02cabd),
          myGridItems(
              "SAMPLE FOUR",
              "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg",
              0xFF02b5e0,
              0xFF02cabd),
          myGridItems(
              "SAMPLE FIVE",
              "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg",
              0xFF02b5e0,
              0xFF02cabd),
          myGridItems(
              "SAMPLE SIX",
              "https://cdn.pixabay.com/photo/2016/03/27/18/54/technology-1283624_960_720.jpg",
              0xFF02b5e0,
              0xFF02cabd),
        ],
      ),
    );
  }

  Widget myGridItems(
      String gridName, String gridImage, int color1, int color2) {
    return InkWell(
      onTap: () {
        Navigator.of(context).pushNamed(
          '/$gridName',
          arguments: gridName,
        );
      },
      child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(24.0),
            gradient: new LinearGradient(
              colors: [
                Color(color1),
                Color(color2),
              ],
              begin: Alignment.centerLeft,
              end: new Alignment(1.0, 1.0),
            ),
          ),
          child: Stack(
            children: <Widget>[
              Opacity(
                opacity: 0.3,
                child: Container(
                  decoration: new BoxDecoration(
                    borderRadius: BorderRadius.circular(24.0),
                    image: DecorationImage(
                      image: NetworkImage(gridImage),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                      child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                          child: Text(
                        "Job",
                        style: TextStyle(color: Colors.white, fontSize: 16),
                      )),
                      SizedBox(width: 10.0),
                      Container(
                          child: Icon(
                        FontAwesomeIcons.compass,
                        color: Colors.white,
                      )),
                      SizedBox(width: 10.0),
                      Container(
                          child: Text(
                        "Guide",
                        style: TextStyle(color: Colors.white, fontSize: 16),
                      )),
                    ],
                  )),
                  SizedBox(height: 10.0),
                  Padding(
                      padding: const EdgeInsets.only(left: 16.0),
                      child: Text(
                        gridName,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.bold),
                      )),
                ],
              )
            ],
          )),
    );
  }
}

class SampleOne extends StatelessWidget {
  final String gridName;
  final String gridImage;

  SampleOne({this.gridName, this.gridImage});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: Column(
          children: [
            Text("$gridName"),
            RaisedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text('Go back!'),
            ),
          ],
        ),
      ),
    );
  }
}

class SampleTwo extends StatelessWidget {
  final String gridName;
  final String gridImage;

  SampleTwo({this.gridName, this.gridImage});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: Column(
          children: [
            Text("$gridName"),
            RaisedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text('Go back!'),
            ),
          ],
        ),
      ),
    );
  }
}

推荐阅读