Textfield returning null; bypassing await - flutter

Im making a counter app and want to be able to change the title of the appbar by taking input from the user using an popup input box.
I am trying to have the user input a name(string) in an AlertDialog with textfield in it and trying to recieve the string in the main page by defining a function for the popup which returns the inputted string when confirm button is pressed. I'm assigning a variable to this function using await in the onPressed() of the main page and then displaying the string variable change in a snackbar. however, the snackbar is appearing as soon i tap on the textfield without even submitting or hitting the confirm button. it looks like either the await isnt working or for some reason the Alertdialog's parent function is returning null as soon as I tap on the textfield.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: CounterApp(),
));
class CounterApp extends StatefulWidget {
#override
_CounterAppState createState() => _CounterAppState();
}
class _CounterAppState extends State<CounterApp> {
int num = 0;
String name = 'MyCounter-1';
Future<String> changeName() async {
final _controller = TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)
),
title: Text('Change counter name'),
content: TextField(
controller: _controller,
onSubmitted: (str) {
//Navigator.of(context).pop(str);
},
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop(_controller.text.toString());
},
child: Text(
'Confirm',
style: TextStyle(
fontSize: 18.0,
),
),
),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Cancel',
style: TextStyle(
fontSize: 18.0,
),
),
),
],
);
},
);
}
void snackBar(BuildContext context, String string) {
final snackbar = SnackBar(content: Text('Counter renamed to $string'),);
Scaffold.of(context).showSnackBar(snackbar);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(name),
centerTitle: true,
actions: <Widget>[
IconButton(
onPressed: () {
setState(() {
num = 0;
});
},
icon: Icon(
Icons.refresh,
size: 35.0,
),
),
Builder(
builder: (context) => IconButton(
onPressed: () async {
setState(() async {
name = await changeName();
snackBar(context, name);
});
},
icon: Icon(
Icons.edit,
size: 35.0,
),
),
),
],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 2,
child: Container(
child: Center(child: Text(
'$num',
style: TextStyle(
fontSize: 75,
),
)),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
child: RaisedButton(
onPressed: () {
setState(() {
num += 1;
});
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0)
),
color: Colors.blue,
child: Text(
'+',
style: TextStyle(
fontSize: 100.0,
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
child: RaisedButton(
onPressed: () {
setState(() {
num -= 1;
});
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0)
),
color: Colors.grey,
child: Text(
'-',
style: TextStyle(
fontSize: 100.0,
),
),
),
)
],
),
);
}
}
As Soon as I tap on the edit button, this happens:
Image of problem

Just Add await keyword before showDialog() and add return statement at last as shown in the below code.
Future<String> changeName() async {
final _controller = TextEditingController();
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
title: Text('Change counter name'),
content: TextField(
controller: _controller,
onSubmitted: (str) {
//Navigator.of(context).pop(str);
},
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop(_controller.text.toString());
},
child: Text(
'Confirm',
style: TextStyle(
fontSize: 18.0,
),
),
),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Cancel',
style: TextStyle(
fontSize: 18.0,
),
),
),
],
);
},
);
return _controller.text;
}

Related

The value 'null' can't be returned from a function with return type 'Widget' because 'Widget' is not nullable

what'd I miss ? is it because dart version or other things ,
environment:
sdk: ">=2.16.1 <3.0.0"
1. error
Error: The value 'null' can't be returned from a function with return
type 'Widget' because 'Widget' is not nullable.
'Widget' is from 'package:flutter/src/widgets/framework.dart'
// Alertdialog box showing
showAlertDialog(BuildContext context) {
AlertDialog alert = AlertDialog(
content: Padding(
padding: const EdgeInsets.only(top: 22.0, bottom: 22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: Text(
"Would you like to get latest updates and notifications?",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
SizedBox(height: 24),
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
FlatButton(
onPressed: () {
setState(() {
snackBarText = "You will not recive notifications.";
});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"DENY",
style:
TextStyle(color: Colors.white, fontSize: 16, height: 1.2),
),
color: Colors.purple,
),
SizedBox(width: 10),
FlatButton(
onPressed: () {
setState(() {
snackBarText = "You will recive notifications.";
});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"ALLOW",
style: TextStyle(
color: Colors.purple, fontSize: 16, height: 1.2),
),
shape: RoundedRectangleBorder(
side: BorderSide(width: 1, color: Colors.purple)),
color: Colors.white,
)
])
],
),
),
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
**2.**error
lib/ua_Screens.dart:29:8: Error: Field '_image' should be initialized
because its type 'File' doesn't allow null.
'File' is from 'dart:io'. File _image;
^^^^^^
File _image;
Future get_image() async {
final image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
I think you write wrong code, try below code hope its help to used. and one thing dont used FlatButton used TextButton because FlatButton is depriciated by flutter.
Refer TextButton
Your Alert Dialog function:
showAlertDialog(BuildContext context) {
return AlertDialog(
content: Padding(
padding: const EdgeInsets.only(top: 22.0, bottom: 22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: Text(
"Would you like to get latest updates and notifications?",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
SizedBox(height: 24),
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
FlatButton(
onPressed: () {
setState(() {});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"DENY",
style:
TextStyle(color: Colors.white, fontSize: 16, height: 1.2),
),
color: Colors.purple,
),
SizedBox(width: 10),
FlatButton(
onPressed: () {
setState(() {});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"ALLOW",
style: TextStyle(
color: Colors.purple, fontSize: 16, height: 1.2),
),
shape: RoundedRectangleBorder(
side: BorderSide(width: 1, color: Colors.purple)),
color: Colors.white,
)
])
],
),
),
);
}
Your Widget:
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return showAlertDialog(context);
},
);
},
child: Text('Pressed Me'),
),
Your result screen->
Your alert dialog->
Your Second error refer my answer here and here

How to fix when BackdropScaffold frontLayer's elements doesn't appear?

Sorry for the bad title:(!
My app should show in the home screen cards and FloatingActionButton, I've created the cards in separate file, so I'm forwarding the data to it, also to store my data I'm using sqlite which I'm new to it..
the FloatingActionButton should appear when I run the application, and I need it to add new cards. I know that the database is empty now, but why the FloatingActionButton is not appearing?
when running it it looks like this.
I had followed a tutorial in the part when using the sqlite, and this is a part of my homeScreen code :
frontLayer: FutureBuilder<List<Reminder>>(
future: _reminders,
builder: (context, snapshot) {
if (snapshot.hasData) {
_currentReminders = snapshot.data!;
return ListView(children: [
...snapshot.data!.map<Widget>((reminder) {
return ReminderCard(
name: reminder.name, details: reminder.details);
}).followedBy([
Scaffold(
backgroundColor: Colors.amber,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black,
child: Icon(Icons.add),
onPressed: () {},
),
)
]).toList(),
Padding(
padding: const EdgeInsets.all(8.0),
),
Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black,
child: Icon(Icons.add),
onPressed: () {}
this is the full code if I didn't paste the right part of my code: https://github.com/RarLasebai/reminder3/blob/main/lib/ui/Screens/homeScreen.dart
i have cloned your project and did a little changes on the HomeScreen
here is how u should do it
import 'package:flutter/material.dart';
import 'package:backdrop/backdrop.dart';
import 'package:untitled/helper.dart';
import 'package:untitled/models/reminder.dart';
import 'package:untitled/ui/widgets/ReminderCard.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
TextEditingController nameController = TextEditingController();
TextEditingController detailsController = TextEditingController();
final _formKey = GlobalKey<FormState>();
late ReminderCard card;
RHelper helper = RHelper();
late Future<List<Reminder>> _reminders;
late List<Reminder> _currentReminders;
//-------------------------Functions----------------
bool status = true;
#override
void initState() {
super.initState();
helper.initializeDatabase().then((value) => {print("------------donne?")});
_loadReminders();
}
void _loadReminders() {
_reminders = helper.getReminders();
if (mounted) setState(() {});
}
//Screen and appBar frontend
#override
Widget build(BuildContext context) {
return BackdropScaffold(
backgroundColor: Colors.white,
appBar: BackdropAppBar(
centerTitle: true,
title: (Text(
'قائمة التذكيرات',
style: Theme.of(context).textTheme.headline1,
)),
),
headerHeight: 110.0,
frontLayer: FutureBuilder<List<Reminder>>(
future: _reminders,
builder: (context, snapshot) {
if (snapshot.hasData) {
_currentReminders = snapshot.data!;
return ListView(children: [
Column(
children: _currentReminders.map<Widget>((reminder) {
return ReminderCard(
name: reminder.name, details: reminder.details);
}).toList(),
),
Padding(
padding: const EdgeInsets.all(8.0),
),
]);
}
return Center(child: Text("Loading>>.."));
},
),
backLayer: BackdropNavigationBackLayer(
items: [
ListTile(
leading: ImageIcon(AssetImage('icons/to-do-list.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("التذكيرات",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('home');
}),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/athkar.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("الأذكار",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('athkar');
}),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/mosque.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("مواقيت الصلاة",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('adhan');
},
),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/Tasbeeh.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("تسبيح",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('tasbeeh');
},
),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/quran.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("مصحف",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('moshaf');
},
),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/tadabur.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("وقفات تدبرية ",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('tadabur');
}),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/information.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("تواصل معنا",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('contact');
})
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
showModalBottomSheet(
useRootNavigator: true,
context: context,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(24),
),
),
builder: (context) {
return StatefulBuilder(
builder: (context, setModalState) {
return Container(
padding: const EdgeInsets.all(32),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (String? value) {
if (value!.isEmpty)
return 'Please enter name';
},
controller: detailsController,
style: TextStyle(
color: Colors.black, fontSize: 15.0),
decoration: InputDecoration(
errorStyle: TextStyle(
color: Colors.red, fontSize: 15.0),
labelText: 'اسم التذكير',
labelStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(5.0)),
),
),
SizedBox(
height: 10,
),
TextFormField(
controller: nameController,
style: TextStyle(
color: Colors.black, fontSize: 15.0),
decoration: InputDecoration(
labelText: 'التفاصيل',
labelStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(5.0)),
),
),
SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () {
setState(() {
if (_formKey.currentState!
.validate()) {
_save();
Navigator.pop(context);
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(
content: Text(
'تم حفظ التذكير')));
}
});
},
child: Text('حفظ'),
)
],
),
),
);
});
},
);
})
);
}
void _save() {
var _reminder = Reminder(
name: nameController.text, details: detailsController.text, save: 0);
helper.insertReminder(_reminder);
_loadReminders();
}
}
and for a athkar project i really suggest that you use provider or riverpod , or any kind of state management

Show drawer over bottom navigation bar in Flutter

I have a drawer in a appbar and need to show it over the bottom navigation bar but can't put both in the same view, I don't know exactly how to do this.
This is what it looks like now and this is what it needs to look like.
This is part of the code of the view where the appbar is
class ContactsPage extends StatefulWidget {
final String title;
final String token;
final String qr;
String code;
final String name;
ContactsPage({this.name, this.token, this.qr, this.code, Key key, this.title})
: super(key: key);
#override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
List<Contact> contactList;
bool showHorizontalBar = false;
bool ready = false;
#override
void initState() {
super.initState();
var userService = new UserService();
userService.getContacts(widget.token).then((value) => {
print(value),
if (value == '0')
{
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => LoginPage()))
}
else if (value == '3')
{
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => LoginPage()))
}
else
{
setState(() {
contactList = value;
ready = true;
})
},
print(contactList),
});
}
void showMessage(String message, [MaterialColor color = Colors.red]) {
_scaffoldKey.currentState..removeCurrentSnackBar();
_scaffoldKey.currentState.showSnackBar(
new SnackBar(backgroundColor: color, content: new Text(message)));
}
_navigateAndDisplaySelection(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scanner(
qr: widget.qr,
token: widget.token,
)),
);
if (result != null) {
showMessage('$result', Colors.red);
}
}
Widget _addPerson() {
return FloatingActionButton(
onPressed: () {
_navigateAndDisplaySelection(context);
},
child: Icon(Icons.group_add),
backgroundColor: Color(0xff83bb37),
);
}
Widget buildMenuIcon() {
return IconButton(
icon: Icon(showHorizontalBar ? Icons.close : Icons.more_horiz),
onPressed: () {
setState(() {
showHorizontalBar = !showHorizontalBar;
});
},
);
}
Widget _simplePopup() => PopupMenuButton<int>(
itemBuilder: (context) => [
PopupMenuItem(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(
Icons.delete,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.favorite,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.mail,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.calendar_today,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.call,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
],
),
)
],
icon: Icon(
Icons.more_horiz,
size: 20,
color: Color(0xff4d4c48),
),
);
Widget _card(String first_name, String last_name, String email) {
return Card(
clipBehavior: Clip.antiAlias,
child: Column(
children: [
SizedBox(
height: 5.0,
),
ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(13.0),
child: Image.asset(
'assets/images/mujer.jpg',
width: 60.0,
height: 70.0,
fit: BoxFit.cover,
),
),
title: Row(
children: [
Text(
first_name,
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff4d4c48)),
),
SizedBox(width: 5.0),
Text(
last_name,
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff4d4c48)),
)
],
),
subtitle: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
email,
style: TextStyle(color: Color(0xff4d4c48)),
),
SizedBox(
height: 5.0,
),
Text(
'Prowebglobal',
style: TextStyle(
color: Color(0xff4d4c48), fontWeight: FontWeight.w600),
),
],
),
),
trailing: _simplePopup(),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ContactDetails(token: widget.token, email: email)));
},
),
SizedBox(
height: 20.0,
),
],
),
);
}
Widget textContainer(String string, Color color) {
return new Container(
child: new Text(
string,
style: TextStyle(
color: color, fontWeight: FontWeight.normal, fontSize: 16.0),
textAlign: TextAlign.start,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
margin: EdgeInsets.only(bottom: 10.0),
);
}
Widget _titulo() {
return new Container(
alignment: Alignment.topLeft,
padding: EdgeInsets.only(left: 20.0),
child: new Text(
'Contactos',
style: TextStyle(
color: Color(0xff83bb37),
fontWeight: FontWeight.bold,
fontSize: 25.0),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.white,
drawer: NavDrawer(
token: widget.token,
),
appBar: AppBar(
centerTitle: true,
backgroundColor: Color(0xfff0f0f0),
title: Image.asset(
'assets/images/logo-iso.png',
height: 50.0,
fit: BoxFit.contain,
alignment: Alignment.center,
),
iconTheme: new IconThemeData(color: Color(0xff707070)),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
},
),
]),
body: Column(children: [
SizedBox(
height: 20.0,
),
Expanded(
flex: 2,
child: _titulo(),
),
Expanded(
flex: 20,
child: Container(
child: ready
? ListView(
children: contactList
.map(
(Contact contact) => _card("${contact.first_name}",
"${contact.last_name}", "${contact.email}"),
)
.toList())
: Center(
child: Image.asset(
"assets/images/logo-gif.gif",
height: 125.0,
width: 125.0,
),
),
),
),
]),
floatingActionButton: _addPerson(),
);
}
}
And this is where de bottom navigation menu is
class HomePage extends StatefulWidget {
HomePage({
this.token,
this.code,
Key key,
}) : super(key: key);
final String token;
final String code;
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String currentPage = 'contacts';
changePage(String pageName) {
setState(() {
currentPage = pageName;
});
}
#override
Widget build(BuildContext context) {
final Map<String, Widget> pageView = <String, Widget>{
"contacts": ContactsPage(
code: widget.code,
token: widget.token,
),
"profile": ProfilePage(
token: widget.token,
),
};
return Scaffold(
body: pageView[currentPage],
bottomNavigationBar: new BottomNavigationDot(
paddingBottomCircle: 21,
color: Colors.black.withOpacity(0.5),
backgroundColor: Colors.white,
activeColor: Colors.black,
items: [
new BottomNavigationDotItem(
icon: Icons.home,
onTap: () {
changePage("contacts");
}),
new BottomNavigationDotItem(icon: Icons.brush, onTap: () {}),
new BottomNavigationDotItem(icon: Icons.notifications, onTap: () {}),
new BottomNavigationDotItem(icon: Icons.favorite, onTap: () {}),
new BottomNavigationDotItem(
icon: Icons.person,
onTap: () {
changePage("profile");
}),
],
milliseconds: 400,
),
);
}
}
Edit:
I have thought on putting de appbar in the same level as de bottom navigation bar but I need to put different options on the appbar depending on the view so I thought on using diferent appbars, that's why I wanted it on the same level as the view.

Theme changing implicitly in Flutter

i'm trying to write a flutter application wHich takes two themes dark and brightness switch case device settings like this:
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Selectable GridView',
theme: ThemeData(
brightness: Brightness.dark,
),
home:HomePage(),
);
with the Brightness.light i have no problem but with the Brightness.dark it works correctly to some alert and when the app have an alert the alert color didn't change to dark and after the alert all the app change theme and color primaryColor:Colors.blue without any code written from me
import 'package:backback/Resultat/testclass.dart' as globals;
import 'package:flutter/cupertino.dart';
import 'package:hardware_buttons/hardware_buttons.dart' as HardwareButtons;
import 'dart:async';
import 'package:flutter/material.dart';
import 'ecouteurT.dart';
import 'flashT.dart';
class Boutontest extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<Boutontest> {
String _latestHardwareButtonEvent;
StreamSubscription<HardwareButtons.VolumeButtonEvent>
_volumeButtonSubscription;
StreamSubscription<HardwareButtons.HomeButtonEvent> _homeButtonSubscription;
StreamSubscription<HardwareButtons.LockButtonEvent> _lockButtonSubscription;
int a, b, c, d;
#override
void initState() {
super.initState();
new Future.delayed(Duration.zero, () {
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)), //this right here
child: Container(
height: 110,
child: Padding(
padding: EdgeInsets.all(0),
child: ListView(
children:
ListTile.divideTiles(context: context, tiles: [
ListTile(
title: Text(
'essayez de appyeez sur les boutons l\'un apres l\'autre et verifiez que tout bouton appyez ets montrez',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onTap: null,
),
ListTile(
title: Text(
'OK',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.deepOrange),
),
onTap: () {
Navigator.of(context).pop(false);
},
)
]).toList())))));
});
_volumeButtonSubscription =
HardwareButtons.volumeButtonEvents.listen((event) {
setState(() {
_latestHardwareButtonEvent = event.toString();
});
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_DOWN') {
b = 0;
}
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_UP') {
c = 0;
}
});
_homeButtonSubscription = HardwareButtons.homeButtonEvents.listen((event) {
setState(() {
a = 0;
_latestHardwareButtonEvent = 'HOME_BUTTON';
});
});
_lockButtonSubscription = HardwareButtons.lockButtonEvents.listen((event) {
setState(() {
d = 0;
_latestHardwareButtonEvent = 'LOCK_BUTTON';
});
});
}
#override
void dispose() {
super.dispose();
_volumeButtonSubscription?.cancel();
_homeButtonSubscription?.cancel();
_lockButtonSubscription?.cancel();
}
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: const Text(
'Hi',
style: TextStyle(color: Colors.black),
),
),
body: Container(
child: Column(children: <Widget>[
Container(
height: height * 0.01,
),
Card(
child: ListTile(
leading: CircularProgressIndicator(
valueColor:
new AlwaysStoppedAnimation<Color>(Colors.deepOrange)),
title: Text(
'Detection des Boutons...',
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text('Element 1/1'),
trailing: InkWell(
onTap: () {
globals.Data.etatbouton('ignore');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Flash()),
);
},
child: Text(
'Ignore>',
style: TextStyle(color: Colors.deepOrange),
),
),
)),
Container(
height: height * 0.02,
),
if (_latestHardwareButtonEvent == 'HOME_BUTTON' || a == 0)
Card(
child: ListTile(
title: Text('Le Bouton Home'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
if (_latestHardwareButtonEvent == 'LOCK_BUTTON' || d == 0)
Card(
child: ListTile(
title: Text('Le Bouton Home'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_DOWN' ||
b == 0)
Card(
child: ListTile(
title: Text('Le Volume Down'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_UP' ||
c == 0)
Card(
child: ListTile(
title: Text('Le Volume Up'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
decoration: BoxDecoration(
border: Border.all(
width: 3.0,
color: Colors.deepOrange,
),
borderRadius: BorderRadius.all(Radius.circular(
30.0) // <--- border radius here
),
),
child: FlatButton(
child: Text(
'Passer au test suivant',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
onPressed: () {
Future.delayed(Duration.zero, () {
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) =>
Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
20.0)), //this right here
child: Container(
height: 180,
child: Padding(
padding: EdgeInsets.all(0),
child: ListView(
children: ListTile.divideTiles(
context: context,
tiles: [
ListTile(
title: Text(
'Tout les boutons appyez sont montrez',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onTap: null,
),
ListTile(
title: Text(
'Oui',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.deepOrange),
),
onTap: () {
globals.Data.etatbouton('1');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Flash()),
);
},
),
ListTile(
title: Text(
'Non',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.deepOrange),
),
onTap: () {
globals.Data.etatbouton('0');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Flash()),
);
},
)
]).toList())))));
});
},
))
]),
),
);
}
}
That's the code of one of the alert I need some help.
import 'package:flutter/material.dart';
import 'package:lamp/lamp.dart';
import 'dart:async';
import 'package:backback/Resultat/testclass.dart' as globals;
import 'batterieT.dart';
class Flash extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<Flash> {
bool _hasFlash = false;
bool _isOn = false;
double _intensity = 1.0;
#override
initState() {
super.initState();
initPlatformState();
}
initPlatformState() async {
bool hasFlash = await Lamp.hasLamp;
print("Device has flash ? $hasFlash");
setState(() { _hasFlash = hasFlash; });
}
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: Text('hi'),
),
body: Container(
//
child: Column(
children: <Widget>[
Container(
height: height*0.01,
),
Card(child:ListTile(
leading: CircularProgressIndicator(valueColor:
new AlwaysStoppedAnimation<Color>(Colors.deepOrange)),
title: Text('Detection Connexion et deconnexion des ecouteurs...',style:TextStyle(fontWeight: FontWeight.bold,color: Colors.deepOrange),),
subtitle: Text('Element 1/1'),
trailing: InkWell(
onTap: (){
globals.Data.etatkit('ignore');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Batterie()),
);
},
child: Text('Ignore>',style: TextStyle(color: Colors.deepOrange),),
),
)),
Container(
height: height*0.02,
),
Container(
margin: const EdgeInsets.only(left: 20.0, right: 20.0),
child:Text(
'Veuillez branchez les ecouteurs plusieurs fois tout en verifiant si le texte afffiche correspond a l\'etat reel',
textAlign: TextAlign.center,)),
if(_isOn==false)
new InkWell(child: Image.asset('assets/flash.jpg'),
onTap:(){_turnFlash();} ,) ,
if(_isOn==true)
new InkWell(child: Image.asset('assets/flashO.jpg'),
onTap:(){_turnFlash();} ,),
Divider(),
Container(
margin: const EdgeInsets.only(left: 20.0, right: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell (child:Text('Ne correspond pas',style: TextStyle(color: Colors.deepOrange),)
, onTap: (){
globals.Data.etatkit('0');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Batterie()),
);
},),
InkWell(child: Text('Correspond',style: TextStyle(color: Colors.deepOrange),),
onTap: (){
globals.Data.etatkit('1');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Batterie()),
);
},)
],
),
)
],
),
),
);
}
Future _turnFlash() async {
_isOn ? Lamp.turnOff() : Lamp.turnOn(intensity: _intensity);
var f = await Lamp.hasLamp;
setState((){
_hasFlash = f;
_isOn = !_isOn;
});
}
_intensityChanged(double intensity) {
Lamp.turnOn(intensity : intensity);
setState((){
_intensity = intensity;
});
}
}
and in this class when the navigator pass to this class I lost dark theme.

Prevent keyboard from appearing on Flutter

I made this very simple aplication but im having a problem with it.
On every action that i do (like deleting something) the keyboard opens automatically.
I want to avoid that, and open the keyboard only when i click on the text form field (line 178 on code).
How can i do that?
I know this is something very simple to make, i have tried some things using focusnode, trying to disable the autofocus, but i didnt could make it work the way i need.
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(
home: Pedidos(),
));
}
class Pedidos extends StatefulWidget {
#override
_PedidosState createState() => _PedidosState();
}
class _PedidosState extends State<Pedidos> with TickerProviderStateMixin {
TabController _tabController;
final _pecasController = TextEditingController();
List _pecasList = [];
var _firstPress = true;
#override
void initState() {
super.initState();
_tabController = new TabController(length: 3, vsync: this);
}
void _addPecas() {
if ((_pecasController.text.isEmpty) ||
((_pecasController.text.trimLeft() == ("")))) {
print("Campo Vazio");
} else {
setState(() {
Map<String, dynamic> newPeca = Map();
newPeca["title"] = _pecasController.text.trimLeft();
//newPeca["ok"] = false;
_pecasController.text = "";
_pecasList.add(newPeca);
// _saveData();
print(_pecasList);
});
}
}
void _enviar() {
if (_pecasList.length < 1) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Lista vazia"),
actions: <Widget>[
new FlatButton(
child: new Text("Fechar"),
onPressed: () {
Navigator.of(context).pop();
}),
]);
});
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Deseja enviar os itens?"),
actions: <Widget>[
new FlatButton(
child: new Text("Fechar"),
onPressed: () {
Navigator.of(context).pop();
}),
new FlatButton(
child: new Text("Enviar"),
onPressed: () async {
Map<String, String> headers = new Map<String, String>();
headers["Content-type"] = "application/json";
headers["Accept"] = "application/json";
//String str = '{"take":55, "skip":"0"}';
final resp = await http.post('http://172.16.14.109:5000/',
//body: str,
body: jsonEncode(_pecasList),
headers: headers);
if (resp.statusCode == 200) {
if (resp.body == "ok") {
setState(() {
print(_pecasList);
_pecasList.clear();
Navigator.of(context).pop();
});
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(
"Erro: entre em contato com o suporte."),
actions: <Widget>[
new FlatButton(
child: new Text("Fechar"),
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).pop();
}),
]);
});
}
}
})
],
);
},
);
}
}
void _apagarTudo() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Deseja limpar a lista?"),
actions: <Widget>[
new FlatButton(
child: new Text("Fechar"),
onPressed: () {
Navigator.of(context).pop();
}),
new FlatButton(
child: new Text("Limpar"),
onPressed: () {
setState(() {
_pecasList.clear();
Navigator.of(context).pop();
});
}),
]);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Solicitação de Peças",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.green,
),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
flex: 8,
child: TextFormField(
controller: _pecasController,
keyboardType: TextInputType.text,
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
decoration: InputDecoration(
hintText: ("Adicionar item"),
),
),
),
Padding(
padding: EdgeInsets.only(right: 15),
),
Expanded(
flex: 2,
child: RaisedButton(
child: Icon(Icons.add, color: Colors.amber),
color: Colors.green,
onPressed: _addPecas,
),
)
],
),
),
Divider(
height: 02.0,
),
Expanded(
child: ListView.builder(
itemCount: _pecasList.length,
itemBuilder: (context, index) {
return ListTile(
dense: true,
key:
Key(DateTime.now().millisecondsSinceEpoch.toString()),
title: Text(
_pecasList[index]["title"],
style: TextStyle(fontSize: 15.0),
),
trailing: Icon(
Icons.delete_forever,
color: Colors.redAccent,
),
onLongPress: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title:
new Text("Deseja remover o item da lista?"),
actions: <Widget>[
new FlatButton(
child: new Text("Fechar"),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text("Excluir"),
onPressed: () {
_pecasList.removeAt(index);
setState(() {
Navigator.of(context).pop();
});
},
),
],
);
},
);
});
}),
),
Row(
mainAxisAlignment: (MainAxisAlignment.center),
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: RaisedButton(
color: Colors.green,
padding: EdgeInsets.all(5.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(4.0),
child: Icon(
Icons.send,
color: Colors.white,
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: Text(
"Enviar",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
],
),
onPressed: _enviar,
)),
Padding(
padding: const EdgeInsets.all(10.0),
child: RaisedButton(
color: Colors.redAccent,
padding: EdgeInsets.all(5.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(4.0),
child: Icon(
Icons.delete,
color: Colors.white,
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: Text(
"Limpar",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
],
),
onPressed: () {
_apagarTudo();
}))
],
)
],
),
);
}
}
Try these changes.
I have controlled enabled field of TextFormField. The TextFormField is disabled when you click on RaisedButton to add the item to list. And TextFormField is enabled when you click on itself.
void _addPecas() {
disableTextFormField();
...
}
bool textFormFieldEnabled = true;
void enableTextFormField(){
setState(() {
textFormFieldEnabled = true;
});
}
void disableTextFormField(){
setState(() {
textFormFieldEnabled = false;
});
}
Widget build(BuildContext context) {
....
child: TextFormField(
controller: _pecasController,
keyboardType: TextInputType.text,
enabled: textFormFieldEnabled,
onTap: () => enableTextFormField(),
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
decoration: InputDecoration(
hintText: ("Adicionar item"),
),
),
...
}