gpt4 book ai didi

flutter - 单击后如何使CircleAvatar更改颜色?

转载 作者:行者123 更新时间:2023-12-03 04:37:35 26 4
gpt4 key购买 nike

 c
我尝试了在StackOverflow此处发布的其他解决方案,但是它们不起作用。有什么建议吗? `
Widget _method(String day){

return InkWell(
child: new Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 16.0,
child: Text(day,
style: TextStyle(
color: Colors.black,
fontSize: 12.0,
fontFamily: 'Product-Sans',
)),
),
),
onTap: () {
setState(() {

});
}
);
}`

最佳答案

有一些插件可以为您完成此操作,但是如果您想从头开始学习,请执行以下操作:
基本上,您保留一个变量_currentSelectedIndex,以跟踪当前选定的图块。当用户按下该图块时,您将调用setState并更新当前图块。然后,您可以配置选定和未选定图块的颜色。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Weekday selector',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _currentSelectedIndex;

final Map<int, String> _weekdayIndices = {
0: 'S',
1: 'M',
2: 'T',
3: 'W',
4: 'T',
5: 'F',
6: 'S',
};

Widget _weekdayTile(int index) {
bool selected = index == _currentSelectedIndex;

Color tileColor = selected ? Colors.red : Colors.white;
Color textColor = selected ? Colors.white : Colors.black;

return Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
child: InkWell(
onTap: () {
setState(() {
_currentSelectedIndex = index;
});
},
child: CircleAvatar(
backgroundColor: tileColor,
radius: 16.0,
child: Text(
_weekdayIndices[index],
style: TextStyle(
color: textColor,
),
),
),
),
);
}

Widget _weekdayPicker() {
List<Widget> tiles = [];

for (int i = 0; i < 7; i++) {
tiles.add(_weekdayTile(i));
}

return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: tiles,
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _weekdayPicker(),
),
);
}
}

关于flutter - 单击后如何使CircleAvatar更改颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63855287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com