How to avoid GlobalKey<NavigatorState> dublicate keys in flutter - flutter

I have nested navigation. When I want to navigate to the home page, I face with dublicate key errors.
class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0;
List<GlobalKey<NavigatorState>> navigatorKeys = [
mainNavigatorKey,
menuNavigatorKey
];
Future<bool> _systemBackButtonPressed() async {
if (navigatorKeys[_selectedIndex].currentState?.canPop() ?? false) {
navigatorKeys[_selectedIndex]
.currentState
?.pop(navigatorKeys[_selectedIndex].currentContext);
}
return false;
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _systemBackButtonPressed,
child: Scaffold(
backgroundColor: Colour.gray6,
bottomNavigationBar:
BottomNavigationMenu((val) => setState(() => _selectedIndex = val)),
body: FadeIndexedStack(
index: _selectedIndex,
children: const [
MainNavigator(),
MenuNavigator(),
],
),
),
);
}
GlobalKey<NavigatorState> mainNavigatorKey = GlobalKey<NavigatorState>();
class _MainNavigatorState extends State<MainNavigator> {
#override
Widget build(BuildContext context) {
return Navigator(
key: mainNavigatorKey,
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute()
Because of this hierarchie I can not navigate to Home page. when I do Navigator.of(context).pushNamed(RouteNames.home) I get an error. How to solve this ?

Related

Rid of elevation of Nested Flutter Navigator 2.0

Try to use Navigation 2.0 for a web project. I added a nested navigator, but I do not like the elevation that comes with the nested Navigator.
Ugly elevation
import 'package:flutter/material.dart';
import 'package:move_to_background/move_to_background.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Router(
routerDelegate: AuthenticationRouterDelegate(),
backButtonDispatcher: RootBackButtonDispatcher(),
),
);
}
}
class AuthenticationRouterDelegate extends RouterDelegate with ChangeNotifier {
bool isAuthenticated = false;
final GlobalKey<NavigatorState> navigatorKey;
AuthenticationRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();
#override
Future<bool> popRoute() async {
print('popRoute AuthenticationRouterDelegate');
MoveToBackground.moveTaskToBack();
return true;
}
#override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
observers: [HeroController()],
pages: [
MaterialPage(
key: ValueKey('MyHomePage'),
child: MyAuthenticationWidget(
onPressed: () {
isAuthenticated = true;
notifyListeners();
},
),
),
if (isAuthenticated)
MaterialPage(
key: ValueKey('NestedNavigatorPage'),
child: NestedRouterWidget(),
),
],
onPopPage: (route, result) {
print('onPopPage AuthenticationRouterDelegate');
if (!route.didPop(result)) return false;
isAuthenticated = false;
notifyListeners();
return true;
},
);
}
// We don't use named navigation so we don't use this
#override
Future<void> setNewRoutePath(configuration) async => null;
}
class MyAuthenticationWidget extends StatelessWidget {
final VoidCallback onPressed;
MyAuthenticationWidget({required this.onPressed}) : super();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
Expanded(
flex: 1,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Side block'),
],
),
),
Expanded(
flex: 2,
child: Center(
child: NestedRouterWidget(),
),
)
],
),
);
}
}
class NestedRouterWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
final childBackButtonDispatcher =
ChildBackButtonDispatcher(Router.of(context).backButtonDispatcher!);
childBackButtonDispatcher.takePriority();
return Router(
routerDelegate: NestedRouterDelegate(),
backButtonDispatcher: childBackButtonDispatcher,
);
}
}
final GlobalKey<NavigatorState> _nestedNavigatorKey =
GlobalKey<NavigatorState>();
class NestedRouterDelegate extends RouterDelegate with ChangeNotifier {
int selectedIndex = 0;
#override
Future<bool> popRoute() async {
print('popRoute NestedRouterDelegate');
return false;
}
#override
Widget build(BuildContext context) {
return Navigator(
key: _nestedNavigatorKey,
observers: [HeroController()],
pages: [
if (selectedIndex == 0)
MaterialPage(
key: ValueKey('ProfilePage'),
child: ProfileWidget(
onPressed: () {},
),
),
if (selectedIndex == 1)
MaterialPage(
key: ValueKey('NestedNavigatorPage'),
child: SettingWidget(),
),
],
onPopPage: (route, result) {
print('onPopPage NestedRouterDelegate');
return false;
},
);
}
// We don't use named navigation so we don't use this
#override
Future<void> setNewRoutePath(configuration) async => null;
}
class ProfileWidget extends StatelessWidget {
final VoidCallback onPressed;
ProfileWidget({required this.onPressed}) : super();
#override
Widget build(BuildContext context) {
// omit
}
}
class SettingWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
// omit
}
}
Full source code on GitHub here https://github.com/AndrewPiterov/flutter_web_nested_navigator/blob/main/lib/main.dart
How to remove this elevation? Thanks!
At the end, figured out the solution is to set fullscreenDialog to true
MaterialPage(
key: ValueKey('ProfilePage'),
fullscreenDialog: true,
child: ProfileWidget(
onPressed: () {},
),
),

Screen navigation in flutter

Update:
The app has two stateful widget screens: Home, and Search. Both screens have search boxes and a bottom navigation.
The problem that needs to be solved is when a user taps the search box at the top of the home screen, the app should take them to the search screen without hiding the bottom navigation (just like what the eBay app does).
I have tried calling the Search class when the user taps the search box on the Home screen. And this approach works. However, the new screen hides the navigation bar at the bottom.
The following code handles the navigation between screens.
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentIndex = 0;
final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Navigator(
key: _navigatorKey,
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case 'Search':
return MaterialPageRoute(builder: (context) => Search());
default:
return MaterialPageRoute(builder: (context) => UserHome());
}
}),
bottomNavigationBar: BottomNavigationBar(
onTap: _onTap,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home),title: Text('Home'))
BottomNavigationBarItem(icon: Icon(Icons.search), title: Text('Search'))
],
),
);
}
void _onTap(int tappedIndex) {
setState(() => _currentIndex = tappedIndex);
switch (tappedIndex) {
case 0:
_navigatorKey.currentState.pushReplacementNamed('Home');
break;
case 1:
_navigatorKey.currentState.pushReplacementNamed('Search');
break;
}
}
}
If you are trying to do this for automated testing. You can do so using widget testing. Widget tests in flutter can simulate button taps and check for the expected output
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
bool home;
#override
void initState() {
super.initState();
home = true;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: home ? UserHome() : Search(),
bottomNavigationBar: BottomNavigationBar(
onTap: _onTap,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(
icon: Icon(Icons.search), title: Text('Search'))
],
),
);
}
void _onTap(int tappedIndex) {
setState(() {
if (tappedIndex == 0) {
home = true;
} else {
home = false;
}
});
}
}
class UserHome extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Center(
child: Container(
color: Colors.yellow,
child: Text('USER HOME'),
),
)
],
);
}
}
class Search extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Center(
child: Container(
color: Colors.green,
child: Text('SEARCH'),
),
)
],
);
}
}
I know this is not exactly very similar to your initial solution but it achieves the behavior you intend.

Flutter search delegate, set a value in the Text Input or load last searched value

I would like to know how I can set a default value for the query in the Flutter Search delegate so that when it is launched, there is a default value the user can change.
I have tried to set query in #override buildLeading() but when it is set like this, the user cannot change the value.
Thank you in advance
class TheSearch extends SearchDelegate<String>{
TheSearch({this.contextPage,this.controller,this.compressionRateSearch});
BuildContext contextPage;
WebViewController controller;
final suggestions1 = ["https://www.google.com"];
#override
String get searchFieldLabel => "Enter a web address";
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(icon:Icon(Icons.clear),onPressed:(){
query = "";
},)
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(icon:AnimatedIcon(
icon:AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),onPressed:(
){
close(context,null);
},);
}
#override
Widget buildResults(BuildContext context) {
}
#override
Widget buildSuggestions(BuildContext context) {
final suggestions = query.isEmpty ? suggestions1 : [];
return ListView.builder(itemBuilder: (content,index) => ListTile(
leading:Icon(Icons.arrow_left),
title:Text(suggestions[index])
),);
}
}
Try this,
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() {
runApp(MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future<void> _showSearch() async {
await showSearch(
context: context,
delegate: TheSearch(),
query: "any query",
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Search Demo"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: _showSearch,
),
],
),
);
}
}
class TheSearch extends SearchDelegate<String> {
TheSearch({this.contextPage, this.controller});
BuildContext contextPage;
WebViewController controller;
final suggestions1 = ["https://www.google.com"];
#override
String get searchFieldLabel => "Enter a web address";
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
},
)
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
},
);
}
#override
Widget buildResults(BuildContext context) {
return null;
}
#override
Widget buildSuggestions(BuildContext context) {
final suggestions = query.isEmpty ? suggestions1 : [];
return ListView.builder(
itemCount: suggestions.length,
itemBuilder: (content, index) => ListTile(
leading: Icon(Icons.arrow_left), title: Text(suggestions[index])),
);
}
}

flutter: child widget not rebuilt after parent rebuild

Version:
Flutter-Version: 1.12.14 channel dev
Dart-Version: 2.7.0
Question:
I wan write a Todo App. when i click floatbutton add a new Todo, but in some cases its not work well.
The problem in Scaffold.body, detials in code.
it work well when i use TodoPage(todoList: _todoList).
_pageList.elementAt(_activeIndex) is not work when i submit textfield .
I found the print('Build Home')print after submit but print('Build TodoPage') not print.
why???
My Code:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget{
#override
Widget build(BuildContext context){
return MaterialApp(
title: 'TodoList',
home: Home(),
);
}
}
class Home extends StatefulWidget{
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home>{
List<String> _todoList = ['a', 'b', 'c'];
TextEditingController _controller;
List<Widget> _pageList;
int _activeIndex;
Widget _curPage;
#override
void initState(){
super.initState();
_activeIndex = 0;
_pageList = [TodoPage(todoList: _todoList,), OtherPage()];
_curPage = _pageList[_activeIndex];
_controller = TextEditingController();
}
#override
Widget build(BuildContext context){
print('build Home');
return Scaffold(
appBar: AppBar(title: Text('Todo'),),
body: _pageList.elementAt(_activeIndex), // this is not work
// body: TodoPage(todoList: _todoList,), // this is work well
floatingActionButton: FloatingActionButton(
onPressed: _openDlg,
child: Icon(Icons.add),
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.list), title: Text('Todo')),
BottomNavigationBarItem(icon: Icon(Icons.favorite), title: Text('Other')),
],
currentIndex: _activeIndex,
selectedItemColor: Colors.blue,
onTap: _onMenuTap,
),
);
}
_onMenuTap(int index){
setState(() {
_activeIndex = index;
});
}
_openDlg(){
showDialog(
context: context,
builder: (BuildContext context){
return SimpleDialog(
children: <Widget>[
TextField(
controller: _controller,
),
SimpleDialogOption(
child: FloatingActionButton(child: Text('submit'), onPressed: _addTodo,),
)
],
);
}
);
}
_addTodo(){
print(_controller.text);
setState(() {
_todoList.add(_controller.text);
});
}
}
class TodoPage extends StatefulWidget{
TodoPage({Key key, this.todoList}): super(key: key);
List<String> todoList;
_TodoPageState createState() => _TodoPageState();
}
class _TodoPageState extends State<TodoPage>{
#override
void initState(){
super.initState();
}
#override
Widget build(BuildContext context){
print('build TodoPage');
return Column(
children: _buildTodoList(),
);
}
List <Widget> _buildTodoList(){
return widget.todoList.map((todo){
return Text(todo, style: TextStyle(fontSize: 30),);
}).toList();
}
}
class OtherPage extends StatelessWidget{
#override
Widget build(BuildContext context){
return Center(child: Text('Other Page'));
}
}
That is logical.
You are reusing an existing instance of a Widget, and widgets are immutable.
As such, the framework notice that the instance of the widget did not change and doesn't call build to optimize performances.
Your problem being, you violated the rule of widgets being immutable, which makes this optimization break your app.
What you did:
class MyState extends State<MyStatefulWidget> {
SomeWidget myWidget = SomeWidget()..someProperty = "initial value";
void onSomething() {
setState(() {
myWidget.someProperty = "new value";
});
}
#override
Widget build(BuildContext context) {
return myWidget;
}
}
What you should instead do:
class MyState extends State<MyStatefulWidget> {
SomeWidget myWidget = SomeWidget(someProperty: "initial value");
void onSomething() {
setState(() {
myWidget = SomeWidget(someProperty: "new value");
});
}
#override
Widget build(BuildContext context) {
return myWidget;
}
}
Alternatively, just don't cache the widget instance at all.

Flutter switch between fragments by supporting back to previous fragment

in this link in SF, #martinseal1987 show us how can we use separated widgets link with android fragments.
I implemented this solution on my project and after running project i dont have any problem to show first widgets as an Fragment, but when i press to back button my screen goes to black and couldn't back to previous widgets as an fragment
i think that is should be this:
Problem is on navigateBack and customPop methods and i can attach fragment by pressing on button
import 'package:flutter/material.dart';
void main()
{
runApp(MaterialApp(
title: 'AndroidMonks',
home: Scaffold(
appBar: AppBar(
title: Text('Androidmonks'),
backgroundColor: Colors.orangeAccent,
),
body: Home(),
),
));
}
class Home extends StatefulWidget {
Home({
Key key,
}) : super(key: key);
#override
State<Home> createState()=>_Home();
}
class _Home extends State<Home> {
String title = "Title";
int _currentIndex = 0;
final List<int> _backstack = [0];
#override
Widget build(BuildContext context) {
navigateTo(_currentIndex);
//each fragment is just a widget which we pass the navigate function
List<Widget> _fragments =[Fragment1(),Fragment2(),Fragment3()];
//will pop scope catches the back button presses
return WillPopScope(
onWillPop: () {
customPop(context);
},
child: Scaffold(
body: Column(
children: <Widget>[
RaisedButton(
child:Text('PRESS'),
onPressed: (){
_currentIndex++;
navigateTo(_currentIndex);
},
),
Expanded(
child: _fragments[_currentIndex],
),
],
),
),
);
}
void navigateTo(int index) {
_backstack.add(index);
setState(() {
_currentIndex = index;
});
_setTitle('$index');
}
void navigateBack(int index) {
setState(() {
_currentIndex = index;
});
_setTitle('$index');
}
customPop(BuildContext context) {
if (_backstack.length - 1 > 0) {
navigateBack(_backstack[_backstack.length - 1]);
} else {
_backstack.removeAt(_backstack.length - 1);
Navigator.pop(context);
}
}
//this method could be called by the navigate and navigate back methods
_setTitle(String appBarTitle) {
setState(() {
title = appBarTitle;
});
}
}
class Fragment2 extends StatefulWidget {
#override
State<Fragment2> createState() => _Fragment2();
}
class _Fragment2 extends State<Fragment2> {
#override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text("_Fragment2"),
onPressed: (){
}),
);
}
}
class Fragment1 extends StatefulWidget {
#override
State<Fragment1> createState() => _Fragment1();
}
class _Fragment1 extends State<Fragment1> {
#override
Widget build(BuildContext context) {
return Center(
child: Text("_Fragment1"),
);
}
}
class Fragment3 extends StatefulWidget {
#override
State<Fragment3> createState() => _Fragment3();
}
class _Fragment3 extends State<Fragment3> {
#override
Widget build(BuildContext context) {
return Center(
child: Text("_Fragment3"),
);
}
}
I fixed some logic in your code please carefully check the changes, if you have any question don't hesitate, here is the working code
import 'package:flutter/material.dart';
void main()
{
runApp(MaterialApp(
title: 'AndroidMonks',
home: Scaffold(
appBar: AppBar(
title: Text('Androidmonks'),
backgroundColor: Colors.orangeAccent,
),
body: Home(),
),
));
}
class Home extends StatefulWidget {
Home({
Key key,
}) : super(key: key);
#override
State<Home> createState()=>_Home();
}
class _Home extends State<Home> {
String title = "Title";
List<Widget> _fragments =[Fragment1(),Fragment2(),Fragment3()];
int _currentIndex = 0;
final List<int> _backstack = [0];
#override
Widget build(BuildContext context) {
//navigateTo(_currentIndex);
//each fragment is just a widget which we pass the navigate function
//will pop scope catches the back button presses
return WillPopScope(
onWillPop: () {
return customPop(context);
},
child: Scaffold(
body: Column(
children: <Widget>[
RaisedButton(
child:Text('PRESS'),
onPressed: (){
_currentIndex++;
navigateTo(_currentIndex);
},
),
Expanded(
child: _fragments[_currentIndex],
),
],
),
),
);
}
void navigateTo(int index) {
_backstack.add(index);
setState(() {
_currentIndex = index;
});
_setTitle('$index');
}
void navigateBack(int index) {
setState(() {
_currentIndex = index;
});
_setTitle('$index');
}
Future<bool> customPop(BuildContext context) {
print("CustomPop is called");
print("_backstack = $_backstack");
if (_backstack.length > 1) {
_backstack.removeAt(_backstack.length - 1);
navigateBack(_backstack[_backstack.length - 1]);
return Future.value(false);
} else {
return Future.value(true);
}
}
//this method could be called by the navigate and navigate back methods
_setTitle(String appBarTitle) {
setState(() {
title = appBarTitle;
});
}
}
class Fragment2 extends StatefulWidget {
#override
State<Fragment2> createState() => _Fragment2();
}
class _Fragment2 extends State<Fragment2> {
#override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text("_Fragment2"),
onPressed: (){
}),
);
}
}
class Fragment1 extends StatefulWidget {
#override
State<Fragment1> createState() => _Fragment1();
}
class _Fragment1 extends State<Fragment1> {
#override
Widget build(BuildContext context) {
return Center(
child: Text("_Fragment1"),
);
}
}
class Fragment3 extends StatefulWidget {
#override
State<Fragment3> createState() => _Fragment3();
}
class _Fragment3 extends State<Fragment3> {
#override
Widget build(BuildContext context) {
return Center(
child: Text("_Fragment3"),
);
}
}
You can achieve this type of navigation using LocalHistoryRoute.of(context).addLocalHistoryEntry and Navigator.pop().