Используя библиотеку drawer_example
, вам нужно внести небольшие изменения, чтобы она заработала.
Добавьте к вашему pocket_widget.dart добавьте это начало:
typedef TitleCallback = void Function(String, int);
Один развы делаете это, ваш Drawer StatefulWidget должен выглядеть следующим образом:
class DrawerWidget extends StatefulWidget {
final TitleCallback callback;
final int tabIndex;
@override
DrawerWidgetState createState() => DrawerWidgetState();
DrawerWidget(this.callback, this.tabIndex);
}
и ваш initState:
@override
void initState() {
selectedDrawerIndex = widget.tabIndex;
selectedProfileIndex = 0;
super.initState();
}
Это будет конструктор для передачи нового значения обратно в ваш main.dartfile.
Внутри ListTile вы можете добавить следующую логику:
ListTile(
leading: Icon(item.icon),
title: Text(item.name),
selected: selectedDrawerIndex == currentIndex,
onTap: () {
final item = getOffsetIndex(drawerGroups, currentIndex);
print('Selected index $selectedDrawerIndex with name ${item.name}');
setState(() {
selectedDrawerIndex = currentIndex;
widget.callback(item.name, selectedDrawerIndex);
});
Navigator.pop(context); // to close the Drawer
},
)
Если вы можете проверить, строка: widget.callback(item.name);
отправляет имя вкладки по обратному вызову, и эта логика можетприменяться в любом месте, где вы хотите изменить свой заголовок.Это может быть даже жестко закодированный заголовок, например:
widget.callback("Second Tab");
Теперь вернемся к вашему файлу main.dart:
class MyApp extends StatefulWidget {
final String title;
ListExample(this.title);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Widget> _fragments = <Widget> [
Container(
child: Text("Fragment One"),
),
Container(
child: Text("Fragment Two"),
),
Container(
child: Text("Fragment Three"),
),
];
String titleAppBar = "Testing";
int tabIndex = 0;
@override
void initState() {
setState(() {
titleAppBar = widget.title;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: widget.title,
home: Scaffold(
appBar: AppBar(
title: Text(titleAppBar),
),
drawer: DrawerWidget((title, index) {
setState(() {
titleAppBar = title;
tabIndex = index;
});
}, tabIndex),
body: _fragments[tabIndex],
),
);
}
}
Окончательный результат: