簡體   English   中英

如何在 Flutter 中的小部件樹中導航到新小部件

[英]How to navigate to new widget as a child in widget tree in Flutter

在下面的示例中,當我推送新的 MaterialPageRoute “Child”時,它在 Flutter 小部件樹中的 MyApp 小部件的同一級別上創建。 我想將它作為小部件 MyApp 的子級,因此 MyApp 將是 Child 小部件的父級。

這是一個完整的代碼:

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

我知道可以使用嵌套導航來完成,但我無法使用導航器。 這是小部件樹的當前結構

您可能需要使用Container更改InkWell小部件,如下所示,因為容器與 inkwell 行為重疊,因此無法執行任何操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM