How to navigate to new widget as a child in widget tree in Flutter

Viewed 349

In the example below when I push new MaterialPageRoute "Child" it is created on the same level as MyApp widget in the Flutter widget tree. I would like to have it as a child of widget MyApp, so MyApp would be a parent of Child widget.

Here is a full code:

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar:AppBar(),
      body: Column(
        children: <Widget>[
          Center(
            child: Text("This is home"),
          ),
          ListView.builder(
            shrinkWrap:true,
          itemCount:10,
          itemBuilder:(context,index){
            return InkWell(
            onTap:(){
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => Child(index)));
            },
            child:Container(
            height:50,
            width:50,
            child:Text("item $index",style:TextStyle(color:Colors.white))));
          }),
          
        ],
      ),
    ),
    );
  }
}

class Child extends StatelessWidget {
  final int index;
  Child(this.index);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:AppBar(),
        body: Container(
      child: Text("Child view $index"),
    ));
  }
}

I understand it can be done using nested navigation but I am unable to use Navigator.this is the current structure of widget tree

1 Answers

You may need to change the InkWell widget with Container as shown below, because the container overlaps the inkwell behavior, thus no action can be performed:

      ListView.builder(shrinkWrap:true, itemCount:10, itemBuilder:(context,index){
        return Container(
          height:50,
          width:50,
          child: InkWell(
            child: Text("item $index",style:TextStyle(color:Colors.white)),
            onTap:(){
             Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => Child(index)));
          })),
      })
Related