Home > Back-end >  How to add a button to the activity of the appbar in flutter?
How to add a button to the activity of the appbar in flutter?

Time:09-23

this is the part that confuses me:

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Startup Name Generator',
      actions: <Widget>[
        IconButton(
          icon: const Icon(Icons.shopping_cart),
          tooltip: 'Open shopping cart',
          onPressed: () {
            // handle the press
          },
        ),
      ],
      home: RandomWords(),
    );
  }
}

I'm following the tutorial provided by google themselves, but it doesn't work:

https://codelabs.developers.google.com/codelabs/first-flutter-app-pt2

I get this error:

The argument type 'List<Widget>' can't be assigned to the parameter type 'Map<Type, Action<Intent>>?'. dart(argument_type_not_assignable)

but the docs state that the actions property is a List<Widget>, so I have no clue what I did wrong

CodePudding user response:

You're working with the wrong parent Widget. The actions of the MaterialApp is not what you're looking for.

Go to your RandomWords Widget, make sure it builds a Scaffold, add an appBar to your Scaffold and set the actions of this AppBar.

You want something like this.

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test appbar'),
        actions: [
          IconButton(
            icon: const Icon(Icons.shopping_cart),
            tooltip: 'Open shopping cart',
            onPressed: () {
              // handle the press
            },
          ),
        ],
      ),
    );
  }
}
  • Related