简体   繁体   中英

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

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. 这是小部件树的当前结构

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)));
          })),
      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM