Place text box in appbar in Flutter - search

I want to implement an Appbar like below where there are a textbox and multiple icons:
The icons can be added in action easily, but how to add the text box and add search action to it. There are many search bar plugins available, but all of them occupy the whole app bar and no way to mention the hints. Can anyone give some idea, it will be a great help for me.

In the title propiery, inside the AppBar, you can pass a widget, which means you can add any component you want, like a TextField. see the example below:
appBar: AppBar(
title: TextField(
decoration: InputDecoration(
hintText: 'Search',
prefixIcon: Icon(Icons.search)
),
),
),
I suggest to you, to wrap this TextField in a GestureDetector, disable the TextField with the proprierty called enable (set to false), and in the onTap method inside the GestureDetector, you can call a showSearch() method.
To call this showSearch(), you'll need to pass a context and a searchDelegate which is a component that extends a class, check this example:
class CustomSearchDelegate extends SearchDelegate {
#override
List<Widget> buildActions(BuildContext context) {
// TODO: implement buildActions
return null;
}
#override
Widget buildLeading(BuildContext context) {
// TODO: implement buildLeading
return null;
}
#override
Widget buildResults(BuildContext context) {
// TODO: implement buildResults
return null;
}
#override
Widget buildSuggestions(BuildContext context) {
// TODO: implement buildSuggestions
return null;
}
}
Source: Implementing search in Flutter
Now, you can do this:
GestureDetector:
onTap: () => showSearch(context: context, delegate: CustomSearchScreen()),
child: ....

Related

How to I update the layout of my home screen when something in the navigation drawer is pressed in Flutter?

I want to make a Navigation drawer application. But instead of a pushing a new screen when something is presses I want update my initial screen. I cannot use setState(){} in my drawer to update the state of my home screen.
Please help me with this.
You can pass a function from your HomeScreen to your Drawer.
In your Drawer:
Class CustomDrawer{
final function updateMainScreen;
CustomDrawer(this.updateMainScreen);
}
In your MainScreen:
child: CustomDrawer(updateScreenFunction), //this function is where your MainScreen state gets changed
This way you can change whatever you want in your HomeScreen from anywhere else.
UPDATE: More Complete example. Note that this is very rough and only so you get an idea of how this works.
HomeScreenState:
class _HomeScreenWidgetState extends State<HomeScreenWidget> {
var containerColor = Colors.red;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: (Text('Hello')),
),
body: Container(
child: Column(
children: <Widget>[
Container(
height: 500,
width: 300,
color: containerColor,
),
CustomDrawer(
changeHomeScreen: changeContainerColor,
)
],
),
));
}
void changeContainerColor(Color col) {
setState(() {
containerColor = col;
});
}
}
The Mock Drawer widget:
class CustomDrawer extends StatelessWidget {
final Function changeHomeScreen;
CustomDrawer({this.changeHomeScreen});
#override
Widget build(BuildContext context) {
return Container(
child: FlatButton(
child: Text("Action in Drawer"),
onPressed: () => changeHomeScreen(Colors.blue),
),
);
}
}
You could also use a Provider for state management. Use the drawer to update the state (model) and use notifylisteners() to update your view. With conditionals pulled from the model, it is realy simple to create a 'single page' app.

Do I have to set the textDirection every time?

I am an absolute beginner to Flutter. I've been trying to follow various books, youtube videos, web guides, and in almost all of them fail when I'm following them at the very first hello world type Widget.
Here is an example of a bit of code given by a guide, which throws up a long error on a red screen on the virtual device, moaning about directionality:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: Text('Hello World'),
));
But if I change it like so, it works:
home: Text('Hello World', textDirection: TextDirection.ltr),
Firstly, do I need to set the textDirection for every text field, or can I set it globally? I'm surprised I have to set it at all - I would have thought left to right would have been the default if it wasn't specified.
Secondly, has flutter changed this recently? Every guide or tutorial or book I found was doesn't seem to have any textDirection set anywhere, has it changed or do I have an issue with my setup/config?
This is odd. You do not have to set textDirection usually. Infact, I never have. I believe your issue is just the missing Scaffold Widget.
Every Page should be contained in a Scaffold, it sets alot of standard values and is very important for many reasons.
return Scaffold(
body: Text("Hello World")
Here is a more complete. Standard starting point for a Flutter App.
main() calls runApp(MyApp)); which in turn sets MyHomePage() as it's starting point. In MyApp you can set some Appwide parameters, like Themes. Your actual UI and Code then goes into MyHomePage.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
//This is your actual UI
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Tryout"),
),
body: Center(
),
);
}
}

How to set dynamic initialRoute based on sharedPrefs value in flutter?

Currently, I am working around routes and i wanted to set initialRoute in my app based on sharedPreferences value.
I am using Statedulwidget for my MaterialAppWidget and using setState() method once the data from sharedPrefs is fetched. But, every time i am getting the same screen.
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int initScreen = 0;
initPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
initScreen = prefs.getInt("initScreen");
print("initScreen ${initScreen}");
setState(() {});
}
#override
void initState() {
super.initState();
initPrefs();
}
#override
Widget build(BuildContext context) {
print("initScreen2 ${initScreen}");
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Authentication',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: initScreen == 0 || initScreen == null
? MediatorPage.routeName
: PopUntilPage.routeName,
routes: {
CloudGroupCreate.routeName: (context) => CloudGroupCreate(),
CloudDashboard.routeName: (context) => CloudDashboard(),
PopUntilPage.routeName: (context) => PopUntilPage(),
ProviderWithFutureBuilderApp.routeName: (context) =>
ProviderWithFutureBuilderApp(),
MediatorPage.routeName: (context) => MediatorPage(),
},
);
}
}
I do not want to use direct widget using home property app. I just want to navigate through only and only using named routes.
Can anyone suggest how to do it properly ?
Thanks.
You need to init SharedPreferences in main() and use WidgetsFlutterBinding.ensureInitialized
You can copy paste run full code below
In demo , I set initScreen to 12
code snippet
int initScreen;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt("initScreen",12);
initScreen = await prefs.getInt("initScreen");
print('initScreen ${initScreen}');
runApp(MyApp());
}
...
initialRoute: initScreen == 0 || initScreen == null
? "/"
: "first",
routes: {
'/': (context) => MyHomePage(title: "demo",),
"first": (context) => FirstPage(),
},
working demo
full code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
//void main() => runApp(MyApp());
int initScreen;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt("initScreen",12);
initScreen = await prefs.getInt("initScreen");
print('initScreen ${initScreen}');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
initialRoute: initScreen == 0 || initScreen == null
? "/"
: "first",
routes: {
'/': (context) => MyHomePage(title: "demo",),
"first": (context) => FirstPage(),
},
//home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class FirstPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("First");
}
}
A simple way to do this is to just use a flag when the load has completed, then, in build:
return _isLoadComplete? MaterialApp() : Container();
Another option, it seems like the MaterialApp is being cached, and initialRoute does not get run the 2nd time. Using a key seems to fix this:
return MaterialApp(
key: UniqueKey(),
//etc
I'd lean towards the first approach, as there's no point having MaterialApp try and show one view, will immediately replacing it with another.

Flutter SerachDelegate modify Hint Text Color and TextField Cursor Color

I'm implementing the search bar using SearchDelegate in my flutter app.
I've overridden the ThemeData appBarTheme(BuildContext context) function to return my main App ThemeData.
However, this only changes the Search views, App Bar Color only. It does not use the Cursor or Hint color defined in the theme.
Appreciate any suggestions.
Are you running your app on the Apple Simulator? Because cursorColor seems to be platform dependent. The documentation for the TextField class states that the cursorColor field
Defaults to [ThemeData.cursorColor] or [CupertinoTheme.primaryColor] depending on [ThemeData.platform].
I had to create a CupertinoThemeData and pass it to the ThemeData of my app in the main.dart file, like this:
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: appBarCursorColorTheme(context),
home: MyHomePage(); // MySearchDelegate contained inside MyHomePage()
);
}
ThemeData appBarCursorColorTheme(BuildContext context) {
final ThemeData theme = Theme.of(context);
CupertinoThemeData ctd =
CupertinoThemeData.raw(null, Colors.white, null, null, null, null);
return theme.copyWith(
cupertinoOverrideTheme: ctd,
);
}

How to detect when a TextField is selected in Flutter?

I have a Flutter TextField which gets covered by the soft keyboard when the field is selected. I need to scroll the field up and out of the way when the keyboard is displayed. This is a pretty common problem and a solution is presented in this StackOverflow post.
I think I have the ScrollController part figured out but how do I detect when the TextField has been selected? There doesn't appear to be any event method (e.g. onFocus(), onSelected(), onTap(), etc).
I tried wrapping the TextField in a GestureDetector but that didn't work either -- apparently the event was never captured.
new GestureDetector(
child: new TextField(
decoration: const InputDecoration(labelText: 'City'),
),
onTap: () => print('Text Selected'),
),
This is such a basic requirement that I know there must be an easy solution.
I suppose you are looking for FocusNode.
To listen to focus change, you can add a listner to the FocusNode and specify the focusNode to TextField.
Example:
class TextFieldFocus extends StatefulWidget {
#override
_TextFieldFocusState createState() => _TextFieldFocusState();
}
class _TextFieldFocusState extends State<TextFieldFocus> {
FocusNode _focus = FocusNode();
TextEditingController _controller = TextEditingController();
#override
void initState() {
super.initState();
_focus.addListener(_onFocusChange);
}
#override
void dispose() {
super.dispose();
_focus.removeListener(_onFocusChange);
_focus.dispose();
}
void _onFocusChange() {
debugPrint("Focus: ${_focus.hasFocus.toString()}");
}
#override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: new TextField(
focusNode: _focus,
),
);
}
}
This gist represents how to ensure a focused node to be visible on the ui.
To be notified about a focus event, you can avoid manually managing widget's state, by using the utility classes FocusScope, Focus.
From the docs (https://api.flutter.dev/flutter/widgets/FocusNode-class.html):
Please see the Focus and FocusScope widgets, which are utility widgets that manage their own FocusNodes and FocusScopeNodes, respectively. If they aren't appropriate, FocusNodes can be managed directly.
Here is a simple example:
FocusScope(
child: Focus(
onFocusChange: (focus) => print("focus: $focus"),
child: TextField(
decoration: const InputDecoration(labelText: 'City'),
)
)
)
The easiest and simplest solution is to add the onTap method on TextField.
TextField(
onTap: () {
print('Editing stated $widget');
},
)
There is another way if your textfield needs to be disabled for some purpose like mine. for that case, you can wrap your textField with InkWell like this,
InkWell(
onTap: () {
print('clicked');
},
child: TextField(
enabled: false,
),
);

Resources