How to Fix problem child is'nt defined in drawer flutter - flutter

class Drawer extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
UserAccountsDrawerHeader(
accountName: Text("Anus"),
accountEmail: Text("Anus#gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundImage: NetworkImage(
"https://images.unsplash.com/photo-1533227268428-f9ed0900fb3b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1158&q=80"),
),
),
ListTile(
leading: Icon(Icons.person),
title: Text("Account"),
subtitle: Text("Personal"),
trailing: Icon(Icons.edit),
),
ListTile(
leading: Icon(Icons.email),
title: Text("Email"),
subtitle: Text("anus#gmail.com"),
trailing: Icon(Icons.send),
),
],
),
);
}
}
How To Fix this Problem In flutter
I Want to Create Drawer but when i try to make drawer in new file for drawer The named parameter 'child' isn't defined.

You used same Widget at definition of that widget.
Here is a working code.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget _buildBody() {
return Drawer();
}
}
class Drawer extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView(
padding: EdgeInsets.zero,
children: [
UserAccountsDrawerHeader(
accountName: Text("Anus"),
accountEmail: Text("Anus#gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundImage: NetworkImage(
"https://images.unsplash.com/photo-1533227268428-f9ed0900fb3b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1158&q=80"),
),
),
ListTile(
leading: Icon(Icons.person),
title: Text("Account"),
subtitle: Text("Personal"),
trailing: Icon(Icons.edit),
),
ListTile(
leading: Icon(Icons.email),
title: Text("Email"),
subtitle: Text("anus#gmail.com"),
trailing: Icon(Icons.send),
),
],
);
}
}

your issue stems from the fact that you used the Name Drawer for the class (your custom widget), which means that the compiler won't know which Drawer widget to use, either the Drawer from the material library or the Drawer that you just defined.
to fix this issue just change the name of the class to AppDrawer or any other name and the compiler will start recognizing that you're trying to use the Drawer defined in the material library.

Related

I wanted to add search bar in my app, but I got some error messages as below

lib/main.dart:143:13: Error: Field 'searchBar' should be initialized because its type 'SearchBar' doesn't allow null.
'SearchBar' is from 'package:flutter_search_bar/src/flutter_search_bar_base.dart' ('../Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_search_bar-2.1.0/lib/src/flutter_search_bar_base.dart').
SearchBar searchBar;
^^^^^^^^^
Error: Cannot run with sound null safety, because the following dependencies
don't support null safety:
package:flutter_search_bar
So I ran dart pub upgrade --null-safety in terminal.
Error: Cannot open file, path = 'C:\Users\Miche\Documents\flutter\version' (OS Error: The system cannot find the file specified.
, errno = 2)
Code: /// Flutter code sample for BottomNavigationBar
// This example shows a [BottomNavigationBar] as it is used within a [Scaffold]
// widget. The [BottomNavigationBar] has three [BottomNavigationBarItem]
// widgets, which means it defaults to [BottomNavigationBarType.fixed], and
// the [currentIndex] is set to index 0. The selected item is
// amber. The `_onItemTapped` function changes the selected item's index
// and displays a corresponding message in the center of the [Scaffold].
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';
void main() => runApp(const MyApp()); // This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Reuse',
style: TextStyle(fontSize: 20),
),
Text(
"Reduce",
style: TextStyle(fontSize: 20),
),
Text(
'Recycle',
style: TextStyle(fontSize: 20),
)
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Food3Rs'),
backgroundColor: Colors.green,
),
drawer: Drawer(
child: ListView(padding: EdgeInsets.zero, children: const <Widget>[
DrawerHeader(
decoration: BoxDecoration(color: Colors.green),
child: Text(
'Food Reduction',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
),
ListTile(
leading: Icon(Icons.bookmark),
title: Text('Saved Recipes'),
),
ListTile(
leading: Icon(Icons.account_circle),
title: Text('Profile'),
),
ListTile(leading: Icon(Icons.settings), title: Text('Settings'))
]),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.food_bank_outlined),
label: ('Reduce'),
backgroundColor: (Colors.lightGreen),
),
BottomNavigationBarItem(
icon: Icon(Icons.food_bank),
label: ('Reuse'),
),
BottomNavigationBarItem(
icon: Icon(Icons.cloud),
label: ('Recycle'),
backgroundColor: (Colors.lightGreen),
)
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
class SearchBarDemoApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Search Bar Demo',
theme: new ThemeData(primarySwatch: Colors.blue),
home: new SearchBarDemoHome());
}
}
class SearchBarDemoHome extends StatefulWidget {
#override
_SearchBarDemoHomeState createState() => new _SearchBarDemoHomeState();
}
class _SearchBarDemoHomeState extends State<SearchBarDemoHome> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
SearchBar searchBar;
AppBar buildAppBar(BuildContext context) {
return new AppBar(
title: new Text('Search Bar Demo'),
actions: [searchBar.getSearchAction(context)]);
}
void onSubmitted(String value) {
setState(() {
var context = _scaffoldKey.currentContext;
if (context == null) {
return;
}
ScaffoldMessenger.maybeOf(context)
?.showSnackBar(new SnackBar(content: new Text('You wrote "$value"!')));
});
}
_SearchBarDemoHomeState() {
searchBar = new SearchBar(
inBar: false,
buildDefaultAppBar: buildAppBar,
setState: setState,
onSubmitted: onSubmitted,
onCleared: () {
print("Search bar has been cleared");
},
onClosed: () {
print("Search bar has been closed");
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: searchBar.build(context),
key: _scaffoldKey,
body: new Center(
child: new Text("Don't look at me! Press the search button!")),
);
}
}
Since you are definately setting the search bar to a non-null value, just not where it's required for the compiler to recognize it, you can use the late keyword:
late SearchBar searchBar;
See the documentation for the late keyword for more information.
The stable version of flutter_search_bar don't support null safety.
Try changing to 3.0.0-dev.1`

Flutter get text from widgets

I am coming from java and now making my very initial steps with flutter.
In my first application I am playing around with the layouts and the buttons and I am facing difficulties getting the button actions to work, probably due to my coming from from java.
In my app I have, among others, the following widgets:
Widget _buttonOne = RaisedButton(
onPressed: () {},
child: Text('Button One', style: TextStyle(fontSize: 20)),
);
final _textContainer =
const Text('Container One', textAlign: TextAlign.center);
Container(
padding: const EdgeInsets.all(8),
child: _textContainer,
color: Colors.teal[200],
),
Now I want to print the text of the button and textchild of the container. How do I achieve that?
CupertinoButton.filled(
child: Text('Button Two'),
onPressed: () {
print(_textContainer); // how do I print the text of the text widget here?
print (_buttonOne. ....); // on java there is a getText() method .... how does this work in flutter?
),
You can access the text of a Text widget by using the data property:
final _textContainer =
const Text('Container One', textAlign: TextAlign.center);
#override
Widget build(BuildContext context) {
return Scaffold(body:
Center(
child: CupertinoButton.filled(
child: Text('Button Two'),
onPressed: () =>
{print(_textContainer.data)},
)
)
);
}
In a similar fashion, you could access the content of the RaisedButton child:
final _raisedButtonText = const Text('Button One', style: TextStyle(fontSize: 20));
Widget _buttonOne = RaisedButton(onPressed: () {}, child: _raisedButtonText);
final _textContainer =
const Text('Container One', textAlign: TextAlign.center);
#override
Widget build(BuildContext context) {
return Scaffold(body:
Center(
child: CupertinoButton.filled(
child: Text('Button Two'),
onPressed: () {
print(_textContainer.data);
print(_raisedButtonText.data);
}
)
)
);
}
You can copy paste run full code below
You can use as to do type casting then access attribute data
code snippet
CupertinoButton.filled(
child: Text('Button Two'),
onPressed: () {
print(_textContainer.data);
print(((_buttonOne as RaisedButton).child as Text).data);
}),
output
I/flutter (30756): Container One
I/flutter (30756): Button One
full code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget _buttonOne = RaisedButton(
onPressed: () {},
child: Text('Button One', style: TextStyle(fontSize: 20)),
);
final _textContainer =
const Text('Container One', textAlign: TextAlign.center);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CupertinoButton.filled(
child: Text('Button Two'),
onPressed: () {
print(_textContainer
.data); // how do I print the text of the text widget here?
print(((_buttonOne as RaisedButton).child as Text).data);
}),
],
),
),
);
}
}

Using FontAwesomeIcons with value from custom class in Flutter

I'm trying to use fontawesome together with flutter. Depending on certain content of an Item I'd like to display a certain Icon from fontawesome.
Transaction(id: 1, title: 'lunch', amount: -23.10, type:'utensils'),
Transaction(id: 2, title: 'new shows', amount: -59.99, type:'tshirt'),
Transaction(id: 3, title: 'Falcon launch', amount: -62000000, type:'rocket')
so, I'd like to use the type as an indicator for my fontawesome icon.
When using FontAwesomeIcons.rocket, everything works quite well.
Column(children: <Widget>[
Card(
child: IconButton(
onPressed: null,
icon: new Icon(FontAwesomeIcons.rocket),
),
elevation: 0,
)
],),
since I'm using the map function I'm able to call the type itself without an issue like Text(tx.type). Is there a way to replace the static (in my case) rocket with the type from my transaction class? I'm trying to avoid if/switch cases at the moment just to get the basics going.
Any help very appreciated.
You can copy paste run full code below
You can use https://pub.dev/packages/icons_helper
just prefix rocket with fa.rocket
code snippet
Icon(getIconUsingPrefix(name: 'fa.rocket'),
color: Theme.of(context).backgroundColor, size: 60.0),
working demo
full code
import 'package:flutter/material.dart';
import 'package:icons_helper/icons_helper.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(title: 'Flutter Demo + Icon Helper Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Map iconMap = {"a":'fa.rocket'};
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
color: Theme.of(context).backgroundColor, size: 60.0),
Icon(getIconUsingPrefix(name: 'fa.rocket'),
color: Theme.of(context).backgroundColor, size: 60.0),
Icon(getIconUsingPrefix(name: iconMap["a"]),
color: Theme.of(context).backgroundColor, size: 60.0),
Text(
'There should be an icon above. It\'s neat, isn\'t?\n\nYou can also push the + button and increment this counter for fun:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

How do I access BuildContext outside of a stateful or stateless widget?

I created a class that extends the AppBar class in Flutter so I can reuse it whenever I need it.
My problem is how do I access the Stateful/Stateless widget build context?
class AppBarLayout extends AppBar {
static final AppController _appController = new AppController();
final GlobalKey<ScaffoldState> _scaffoldKey;
final String appBarTitle;
AppBarLayout(this.appBarTitle,this._scaffoldKey): super(
title: Text(appBarTitle),
leading: IconButton(
onPressed: () => _scaffoldKey.currentState.openDrawer(),
iconSize: 28,
icon: Icon(Icons.menu,color: Colors.white),
),
actions: <Widget>[
IconButton(
onPressed: () => _appController.signOut().then((_) {
_appController.navigateTo(context, new GoogleSignView());
}),
icon: Icon(Icons.account_box),
padding: EdgeInsets.all(0.0),
),
],
);
}
You would need to wrap your Scaffold in a Staless or Stateful widget, so you can get the context, e.g.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarLayout(GlobalKey(debugLabel: 'someLabel'), appBarTitle: 'The Title', context: context,),
body: Center(
child: Column(
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),
),
);
}
}
class AppBarLayout extends AppBar {
final GlobalKey<ScaffoldState> _scaffoldKey;
final String appBarTitle;
final BuildContext context;
AppBarLayout(this._scaffoldKey, {this.appBarTitle, this.context}): super(
title: Text(appBarTitle),
leading: IconButton(
onPressed: () => _scaffoldKey.currentState.openDrawer(),
iconSize: 28,
icon: Icon(Icons.menu,color: Colors.white),
),
actions: <Widget>[
IconButton(
onPressed: () {
print('Button pressed');
},
icon: Icon(Icons.account_box),
padding: EdgeInsets.all(0.0),
),
],
);
}
Here I'm using a very similar Widget of what you have.

Style clipboard in flutter

I am looking for a way to style the clipboard actions without touching textTheme/button property of the main style theme. Is this even possible?
Seems like the style is directly tied to the theme. Not the best idea but if you really wanted to you would need to create a custom popup and handle all the actions yourself.
This should get you started...
Output:
Code:
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(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _controller = new TextEditingController();
final _textfieldFocusNode = new FocusNode();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: GestureDetector(
// intercept all pointer calls
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScope.of(context).requestFocus(_textfieldFocusNode);
},
onLongPress: () {
showMenu(
context: context,
// TODO: Position dynamically based on cursor or textfield
position: RelativeRect.fromLTRB(0.0, 300.0, 300.0, 0.0),
items: [
PopupMenuItem(
child: Row(
children: <Widget>[
// TODO: Dynamic items / handle click
PopupMenuItem(
child: Text(
"Paste",
style: Theme.of(context)
.textTheme
.body2
.copyWith(color: Colors.red),
),
),
PopupMenuItem(
child: Text("Select All"),
),
],
),
),
],
);
},
child: IgnorePointer(
// ensures textfield doesn't overrule GestureDetector
child: TextField(
focusNode: _textfieldFocusNode,
controller: _controller,
),
),
),
)
],
),
),
);
}
}