Home > Software design >  Flutter: How can I make my appbar title (which is an image) redirect to home page?
Flutter: How can I make my appbar title (which is an image) redirect to home page?

Time:06-13

I have a top menu in my app, typical like on an online store (long image which is a logo of my shop on the left side and humburger menu on the right side). I am struggling with making the logo redirecting to home page. Is that option even possible? I was trying many things but I get only errors. I am new in all of that and I would appreciate some help.

This is my appBar code which is a separate dart file as I didn't want to duplicate this code in every Scaffold:

    import 'package:flutter/material.dart';

final appBar = AppBar(
  actions: <Widget>[
    
    Padding(
        padding: EdgeInsets.only(right: 35.0),
        child: GestureDetector(
          onTap: () {},
          child: Icon(Icons.menu),
        )),
  ],
  backgroundColor: Colors.black,
  title: Image.asset(
    'images/logo.png',
    fit: BoxFit.scaleDown,
    height: 30,
    width: 200,
  ),
);

CodePudding user response:

Try to wrap your image with a gesture detector then do navigation inside its ontap callback. compare with code below ... ( NB* do some more reading on navigation https://docs.flutter.dev/cookbook/navigation/navigation-basics )

appBar: AppBar(
    title: GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const HomePage()),
        );
      },
      child: Image.asset(
        'images/logo.png',
        fit: BoxFit.scaleDown,
        height: 30,
        width: 200,
      ),
    ),
  ), 

CodePudding user response:

I have another solution just as collo54 shared wrap your image directly in a "GestureDetector" but I would suggest for that kind of Appbar creating a new file "my_app_bar.dart" and creating a statelessWidget that you will just need to call each time you want to show your CustomAppbar widget, like so:

class MyAppBar extends StatelessWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const HomePage()),
          );
        },
        child: Image.asset(
          'images/logo.png',
          fit: BoxFit.scaleDown,
          height: 30,
          width: 200,
        ),
      ),
    );
  }
}

And then in your HomePage or in whatever page you will just need to call it like so:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(),
      body: Container(),
    );
  }

Hope I was able to help you with your question, If you can't access your context you can allways add a global const with a navigatorKey and the call it with the currentContext, makes things real easy!

Good luck!

  • Related