Rifat Hossain
Rifat Hossain

Reputation: 97

Page routing using List index in Flutter

I am a newbie in Flutter and Programming. I am trying to create a list view (of cards) with ListViewBuilder to show 'Page Title' the respective Named Route to navigate to the page. Presently I was able to generate the 'Page Title' from a List. But I could not generate the Route. How is it possible to do? I have added my code below:

import 'package:flutter/material.dart';

import 'page1.dart';
import 'page2.dart';
import 'page3.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Learning Flutter',
      theme: ThemeData(
        primarySwatch: Colors.cyan,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    List<String> contentList = [
      'open page 1',
      'open page 2',
      'open page 3',
    ];

List<Route> myRoute = [
  //I want to add the list of pages here
];

return Scaffold(
  appBar: AppBar(
    title: Text('Learning Flutter'),
    centerTitle: true,
  ),
  body: ListView.builder(
    itemCount: contentList.length,
    itemBuilder: (context, index) {
      return Card(
        child: ListTile(
          leading: CircleAvatar(
            backgroundImage: AssetImage('images/ic_launcher_round.png'),
          ),
          title: Text(contentList[index]),
          trailing: Icon(Icons.arrow_forward),
          onTap: () {
            //I want to add the route dynamically based on the List index
          },
        ),
      );
    },
  ),
);

} }

Upvotes: 0

Views: 1959

Answers (1)

Igniti0n
Igniti0n

Reputation: 151

    List<Route> myRoute = [
      "MaterialPageRoute(builder: (_) => Page1() )",
      "MaterialPageRoute(builder: (_) => Page2() )",
      "MaterialPageRoute(builder: (_) => Page3() )",
    ];

and

    onTap: () {
      Navigator.of(context).push(myRoute[index]);
    },

This should work.

But I recommend later to use named routes, and use .pushNamed("routeName");

You can define in each page a route name, for ex. in Page1():

   static final routeName = "/page1"; // could be static const

and then call

    Navigator.of(context).pushNamed(Page1.routeName);

so if you want to do that with your code you can mby have:

    List<String> routes= [
      Page1.routeName,
      Page2.routeName,
      Page3.routeName,
    ];

and

    onTap: () {
      Navigator.of(context).pushNamed(routes[index]);
    },

Upvotes: 2

Related Questions