如何在flutter中使用onTap更改Appbar颜色?

carvr3hs  于 2023-03-31  发布在  Flutter
关注(0)|答案(2)|浏览(132)

我尝试在ListTile中使用onTap更改Appbar的背景色

ListTile(
              title: const Text('Black'),
              leading: const Icon(Icons.label),
              onTap: () {
                setState(() {
                  AppBar(
                    backgroundColor: Colors.black,
                  );
                });

                // Navigator.pop(context);
              },
            ),

这是我的代码,但是它不工作。有人能帮助我吗?

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        fontFamily: 'FontDelicious',
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  final bool _pinned = true;
  final bool _snap = true;
  final bool _floating = true;

  late TabController controller;
  int _selectedIndex = 0;
  final ScrollController _homeController = ScrollController();

  @override
  void initState() {
    super.initState();
    controller = TabController(
      length: 2,
      vsync: this,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            pinned: _pinned,
            snap: _snap,
            floating: _floating,
            expandedHeight: 160.0,
            flexibleSpace: FlexibleSpaceBar(
              title: const Text(
                'UTS - KARYAWAN',
                style: TextStyle(color: Colors.black),
              ),
              centerTitle: true,
              background: Image(
                image: NetworkImage(
                    'https://hariliburnasional.com/wp-content/uploads/2020/10/Tempat-Wisata-di-Bali.jpg'),
                fit: BoxFit.cover,
              ),
              collapseMode: CollapseMode.pin,
            ),
            bottom: TabBar(
              tabs: const [
                Tab(icon: Icon(Icons.two_wheeler)),
                Tab(icon: Icon(Icons.directions_car)),
              ],
              controller: controller,
            ),
          ),
          SliverFillRemaining(
            child: TabBarView(
              controller: controller,
              children: const [
                Image(
                  image: NetworkImage(
                      'https://cdn.autoportal.com/bp-v3/img/models/49/e/ducati-1299-panigale-r-final-edition-14.jpg'),
                  fit: BoxFit.cover,
                ),
                Image(
                  image: AssetImage('assets/images/toyota_supra.jpg'),
                  fit: BoxFit.cover,
                ),
              ],
            ),
          ),
        ],
      ),

      // DRAWER NAV

      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            const UserAccountsDrawerHeader(
              accountName: Text('Muh Hilman Sholehudin'),
              accountEmail: Text('ahilman3107@gmail.com'),
              currentAccountPicture: CircleAvatar(
                  foregroundImage: AssetImage('assets/images/hilman.png')),
              otherAccountsPictures: [
                CircleAvatar(
                    foregroundImage: AssetImage('assets/images/hilman.png')),
                CircleAvatar(
                    foregroundImage: AssetImage('assets/images/hilman.png')),
              ],
            ),
            ListTile(
              title: const Text('Home'),
              leading: const Icon(Icons.home),
              onTap: () => {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const SecondRoute(),
                  ),
                ),

                // Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Favorite'),
              leading: const Icon(Icons.favorite_border),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            const Padding(
              padding: EdgeInsets.all(14.0),
              child: Text('Label'),
            ),
            ListTile(
              title: const Text('Black'),
              leading: const Icon(Icons.label),
              onTap: () {
                setState(() {
                  AppBar(
                    backgroundColor: Colors.black,
                  );
                });

                // Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Grey'),
              leading: const Icon(Icons.label),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Blue'),
              leading: const Icon(Icons.label),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      // BOTTOM NAVIBAR

      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.open_in_new_rounded),
            label: 'Open Dialog',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        onTap: (int index) {
          switch (index) {
            case 0:
              // only scroll to top when current index is selected.
              if (_selectedIndex == index) {
                _homeController.animateTo(
                  0.0,
                  duration: const Duration(milliseconds: 500),
                  curve: Curves.easeOut,
                );
              }
              break;
            case 1:
              showModal(context);
              break;
          }
          setState(
            () {
              _selectedIndex = index;
            },
          );
        },
      ),
    );
  }

  void showModal(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          //position
          mainAxisSize: MainAxisSize.min,
          // wrap content in flutter
          children: const <Widget>[
            Text("NIM  : 19255024"),
            Text("Nama : Muh Hilman Sholehudin"),
            Text("Kelas : Karyawan")
          ],
        ),
        actions: <TextButton>[
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('Close'),
          )
        ],
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  const SecondRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Route'),
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}

这是我的完整代码

yqlxgs2m

yqlxgs2m1#

AppBar必须放置在小部件树中(构建函数中)。

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(...)
      appbar: AppBar() // Your AppBar 
  }

然后,您需要在您的状态中声明一个新变量,就像对selectedIndex所做的那样。

Color _appBarColor = Colors.red

最后,您可以将backgroundColor: _appBarColor添加到您的应用程序栏和

setState(() {
_appBarColor = newColor
}

到onTap功能

qv7cva1a

qv7cva1a2#

如果你想要的是改变点击appBar的颜色,你需要先创建一个局部变量来改变AppBar的颜色

Color appBarColor = Colors.red;

然后创建一个函数来改变它

void changeColorOfBar(Color color) {
    setState(() {
      appBarColor = color;
    });
  }

在Scaffold中,您需要将AppBar Package 在GestureDetector中,并将其 Package 在PreferredSize小部件中

return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60.0), // set the height that you want for your AppBar
        child: GestureDetector(
          onTap: () {
            if (appBarColor == Colors.red) {
              changeColorOfBar(Colors.blue);
            } else {
              changeColorOfBar(Colors.red);
            }
          },
          child: AppBar(
            backgroundColor: appBarColor,
            title: const Text(
              "Change Color",
              style: TextStyle(
                color: Colors.white,
                fontSize: 24,
              ),
            ),
          ),
        ),
      ),
      
    );

相关问题