[英]How to change active drawer text color in Flutter?
import 'package:flutter/material.dart';
import './screens/recents_screen.dart';
import './screens/favourites_screen.dart';
class MainDrawer extends StatefulWidget {
const MainDrawer({Key? key}) : super(key: key);
@override
State<MainDrawer> createState() => _MainDrawerState();
}
class _MainDrawerState extends State<MainDrawer> {
var texts = [
{
'title': 'Home',
'path': '/',
},
{
'title': 'Favourite',
'path': FavouritesScreen.routeName,
},
{
'title': 'Recent Search',
'path': RecentsScreen.routeName,
},
];
int _currentSelected = 0;
@override
Widget build(BuildContext context) {
return Drawer(
child: Padding(
padding: const EdgeInsets.only(top: 30, left: 20),
child: Column(children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: texts.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
texts[index]['title'] as String,
style: TextStyle(
fontSize: 16,
letterSpacing: 0.5,
height: 0.36,
color: _currentSelected == index
? Colors.black
: Colors.grey,
fontFamily: 'Roboto Regular'),
),
onTap: () {
setState(() {
_currentSelected = index;
});
Navigator.of(context)
.pushReplacementNamed(texts[index]['path'] as String);
},
);
},
),
),
]),
),
);
}
}
我想將活動抽屜文本顏色設置為黑色,將非活動屏幕設置為灰色。
當我打開抽屜時,“主頁”的文字顏色為黑色,所有其他屏幕標題始終為灰色。 點擊時它工作正常,即點擊的屏幕標題設置為黑色,其他設置為灰色。 但是當打開抽屜時,它總是顯示主屏幕為活動狀態。 如何糾正?
根據您的代碼,這實際上是我希望發生的事情。 在您的 state 中,您設置
int _currentSelected = 0;
這意味着抽屜中的第一個項目(在本例中為Home
)將默認選中,直到您點擊另一個項目。例如,如果您將其初始化為 -1,則默認情況下所有選項都應為灰色。
int _currentSelected = -1; // not an index, so no item will be black
也許更好的是,如果你告訴你的抽屜哪個項目是活動的,給定父窗口小部件。 說這樣的話:
// in the parent state
String routePath = '/';
Widget build(BuildContext context) {
return Scaffold(
...
drawer: MainDrawer(
path: routePath, // pass the route path to the drawer
),
);
}
然后在你的抽屜里,你可以使用這個路徑來 select 正確的索引:
class MainDrawer extends StatefulWidget {
final String path;
// Add path to the arguments, with home as default
const MainDrawer({Key? key, String path = '/'}) : super(key: key);
@override
State<MainDrawer> createState() => _MainDrawerState();
}
class _MainDrawerState extends State<MainDrawer> {
var texts = [
{
'title': 'Home',
'path': '/',
},
{
'title': 'Favourite',
'path': FavouritesScreen.routeName,
},
{
'title': 'Recent Search',
'path': RecentsScreen.routeName,
},
];
int _currentSelected = -1;
@override
void initState() {
super.initState();
// Select the item that is currently selected (given the parent)
var currentText = texts.firstWhere((element) => element.path == widget.path);
// Put that in the state (to nicely select the current index)
_currentSelected = texts.indexOf(currentText);
}
...
}
我希望這能讓你走上正軌。 您甚至可以嘗試使用上下文訪問當前路由名稱以自動獲取當前路由名稱並使用它來突出顯示當前項目。 您可以使用ModalRoute.of(context)
https://api.flutter.dev/flutter/widgets/ModalRoute/of.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.