Flutter: IconButton не получает onPressed function()

#flutter

#трепетание

Вопрос:

Я создал пользовательский макет ниже:

 class CustomLayout extends StatelessWidget {
  final Widget leading;
  final String title;
  final Widget body;
  final List<Widget> bottomBar;

  const CustomLayout({
    Key key,Widget leading, String title, Widget body, this.bottomBar
  }):leading = leading ?? const SizedBox(height: 0,),
    title = title ?? "",
    body = body ?? const SizedBox(),
    super(key: key)
  ;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Stack(
          alignment: Alignment.topLeft,
          children: [
            /// Background
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("images/background.jpg"),
                  fit: BoxFit.cover
                )
              ),
            ),
            /// custom
            Column(
              children: [
                /// SimpleAppbar
                SizedBox(
                  height: (title == "")? 0 : 50,
                  width: MediaQuery.of(context).size.width,
                  child: Stack(
                    alignment: Alignment.centerLeft,
                    children: [
                      Center(
                        child: Text(
                          title,
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 24
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.only(left:4.0,top: 4.0),
                        child: leading,
                      ),
                    ],
                  ),
                ),
                /// body
                Expanded(child: body),
                /// bottomBar
                SizedBox(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: bottomBar == null ? [SizedBox()]:bottomBar,
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
 

и используйте этот макет:

 CustomLayout(
  leading: IconButton(
    icon: Icon(
      Icons.arrow_back,
      color: Colors.white,
    ),
    onPressed: (){
      Navigator.of(context).pop();
    },
  ),
  body: // my code
);
 

ведущий параметр не может быть нажат, я искал и получил несколько подсказок, которые были бы моим стеком, но я проверял много раз. нижняя панель и параметры тела по-прежнему работают нормально. Помогите мне !……………………………………………………………………………………………………………………………………………………………………………………………………………………………………..

Ответ №1:

Как правило, стек используется для многоуровневого формата, поэтому вы использовали расширенный для тела в пользовательском макете, поэтому он занимает всю ширину и высоту экрана и находится в верхней части главного значка, поэтому значок никогда не нажимается, поэтому я изменил некоторые вещи в вашем макетепроверьте это.

 import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SampleApp(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class SampleApp extends StatefulWidget {
  @override
  _SampleAppState createState() => _SampleAppState();
}

class _SampleAppState extends State<SampleApp> {
  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Your app'),
        ),
        body: Container(
          child: CustomLayout(
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back,
                  color: Colors.black,
                  size: 20,
                ),
                onPressed: () {
                  print('This is the tap');
                },
              ),
              body: Text('This is your body') // my code
              ),
        ));
  }
}

class CustomLayout extends StatelessWidget {
  final Widget leading;
  final String title;
  final Widget body;
  final List<Widget> bottomBar;

  const CustomLayout(
      {Key key, Widget leading, String title, Widget body, this.bottomBar})
      : leading = leading ??
            const SizedBox(
              height: 0,
            ),
        title = title ?? "",
        body = body ?? const SizedBox(),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Container(
          child: Stack(
            alignment: Alignment.topLeft,
            children: [
              /// Background
              Container(
                decoration: BoxDecoration(),
              ),

              /// custom
              Column(
                children: [
                  /// SimpleAppbar
                  SizedBox(
                    height: (title == "") ? 0 : 50,
                    width: MediaQuery.of(context).size.width,
                    child: Stack(
                      alignment: Alignment.centerLeft,
                      children: [
                        Center(
                          child: Text(
                            title,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 24),
                          ),
                        ),
                      ],
                    ),
                  ),

                  /// body
                  Expanded(child: body),

                  /// bottomBar
                  SizedBox(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: bottomBar == null ? [SizedBox()] : bottomBar,
                    ),
                  ),
                ],
              ),
              Container(
                padding: const EdgeInsets.only(left: 4.0, top: 5.0),
                child: leading,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

Дайте мне знать, если это сработает