connect to open wireless by using wifi_configuration Flutter - flutter

may i ask how to connect to an open hotspot - wireless- by using wifi_configuration package
cause i just found a method that allow to connect to encrypted wireless networks.
WifiConfiguration.connectToWifi("wirelessname","wirelesspassword","packagename");
inside WifiConfiguration class there is just one method that can be used for connecting.
is there any other library that can connect to an open hotspot or is there a way to do that by using wifi_configuration library ?
Apple mentioned that we need just two parameters to pass which is of course the ssid and the packagename
init(ssid: String)
Creates a new hotspot configuration, identified by an SSID, for an open Wi-Fi network.
i override the method connectToWifi to receive just one parameter but this didn't work.
thanks in advance

You can copy paste run full code below
You can use package https://pub.dev/packages/wifi_utils
You can call Wifi.connection and provide ssid and password
code snippet
import 'package:wifi/wifi.dart';
...
Future<Null> connection() async {
Wifi.connection(ssid, password).then((v) {
print(v);
});
}
working demo
full code
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wifi/wifi.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Wifi',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _wifiName = 'click button to get wifi ssid.';
int level = 0;
String _ip = 'click button to get ip.';
List<WifiResult> ssidList = [];
String ssid = '', password = '';
#override
void initState() {
super.initState();
loadData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Wifi'),
centerTitle: true,
),
body: SafeArea(
child: ListView.builder(
padding: EdgeInsets.all(8.0),
itemCount: ssidList.length + 1,
itemBuilder: (BuildContext context, int index) {
return itemSSID(index);
},
),
),
);
}
Widget itemSSID(index) {
if (index == 0) {
return Column(
children: [
Row(
children: <Widget>[
RaisedButton(
child: Text('ssid'),
onPressed: _getWifiName,
),
Offstage(
offstage: level == 0,
child: Image.asset(
level == 0 ? 'images/wifi1.png' : 'images/wifi$level.png',
width: 28,
height: 21),
),
Text(_wifiName),
],
),
Row(
children: <Widget>[
RaisedButton(
child: Text('ip'),
onPressed: _getIP,
),
Text(_ip),
],
),
TextField(
decoration: InputDecoration(
border: UnderlineInputBorder(),
filled: true,
icon: Icon(Icons.wifi),
hintText: 'Your wifi ssid',
labelText: 'ssid',
),
keyboardType: TextInputType.text,
onChanged: (value) {
ssid = value;
},
),
TextField(
decoration: InputDecoration(
border: UnderlineInputBorder(),
filled: true,
icon: Icon(Icons.lock_outline),
hintText: 'Your wifi password',
labelText: 'password',
),
keyboardType: TextInputType.text,
onChanged: (value) {
password = value;
},
),
RaisedButton(
child: Text('connection'),
onPressed: connection,
),
],
);
} else {
return Column(children: <Widget>[
ListTile(
leading: Image.asset('images/wifi${ssidList[index - 1].level}.png',
width: 28, height: 21),
title: Text(
ssidList[index - 1].ssid,
style: TextStyle(
color: Colors.black87,
fontSize: 16.0,
),
),
dense: true,
),
Divider(),
]);
}
}
void loadData() async {
Wifi.list('').then((list) {
setState(() {
ssidList = list;
});
});
}
Future<Null> _getWifiName() async {
int l = await Wifi.level;
String wifiName = await Wifi.ssid;
setState(() {
level = l;
_wifiName = wifiName;
});
}
Future<Null> _getIP() async {
String ip = await Wifi.ip;
setState(() {
_ip = ip;
});
}
Future<Null> connection() async {
Wifi.connection(ssid, password).then((v) {
print(v);
});
}
}

Related

Save calculated data on screen through shared preferences

I have fetch a temperature converter code from a GitHub repository. I want to show my calculated data history on screen whenever I press Convert button through shared preferences. Can anyone help me out?
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.green,
),
home: TempApp(),
);
}
}
class TempApp extends StatefulWidget {
#override
TempState createState() => TempState();
}
class TempState extends State<TempApp> {
double? input;
double? output;
bool? fOrC;
late SharedPreferences prefs;
#override
void initState() {
super.initState();
input = 0.0;
output = 0.0;
fOrC = true;
}
#override
Widget build(BuildContext context) {
TextField inputField = TextField(
keyboardType: TextInputType.number,
onChanged: (str) {
try {
input = double.parse(str);
} catch (e) {
input = 0.0;
}
},
decoration: InputDecoration(
labelText:
"Input a Value in ${fOrC == false ? "Fahrenheit" : "Celsius"}",
),
textAlign: TextAlign.center,
);
AppBar appBar = AppBar(
title: Text("Temperature Calculator"),
);
Container tempSwitch = Container(
padding: EdgeInsets.all(15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Fahrenheit"),
Radio<bool>(
groupValue: fOrC,
value: false,
onChanged: (v) {
setState(() {
fOrC = v;
});
}),
Text("Celsius"),
Radio<bool>(
groupValue: fOrC,
value: true,
onChanged: (v) {
setState(() {
fOrC = v;
});
}),
SizedBox(
height: 90,
)
],
),
);
Container calcBtn = Container(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: const Size(200, 50),
maximumSize: const Size(200, 50),
textStyle: const TextStyle(fontSize: 20)),
child: Text("Convert"),
onPressed: () {
setState(() {
fOrC == false
? output = (input! - 32) * (5 / 9)
: output = (input! * 9 / 5) + 32;
});
AlertDialog dialog = AlertDialog(
content: fOrC == false
? Text(
"${input?.toStringAsFixed(2)} F : ${output?.toStringAsFixed(2)} C")
: Text(
"${input?.toStringAsFixed(2)} C : ${output?.toStringAsFixed(2)} F"),
);
showDialog(builder: (context) => dialog, context: context);
print('output');
print('input');
},
),
);
return Scaffold(
appBar: appBar,
body: Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
inputField,
tempSwitch,
calcBtn,
],
),
),
);
}
}
I tried of getting string value but I don't understand that how to get read and save data of user input? I am expecting to have a calculated data on screen with input and result data whenever I press the Convert button.

How to send a data from listview screen to form screen using flutter

I am trying to send a data from ontap listview screen to form screen like image below. I have searched many references on google but I can't find any references that can help me, if you can provide solutions or references, I will greatly appreciate it.
enter image description here
This is my sample code (ListPage Screen) :
const ListPage({Key? key}) : super(key: key);
#override
State<ListPage> createState() => _ListPageState();
}
class _ListPageState extends State<ListPage> {
TextEditingController textFieldController = TextEditingController();
var _controller = TextEditingController();
late bool searching, error;
var data;
late String query;
String dataurl = "https://www.something.co.id/mobile/search_data.php";
#override
void initState() {
searching = true;
error = false;
query = "";
super.initState();
}
void getSuggestion() async {
//get suggestion function
var res = await http
.post((Uri.parse(dataurl + "?query=" + Uri.encodeComponent(query))));
//in query there might be unwant character so, we encode the query to url
if (res.statusCode == 200) {
setState(() {
data = json.decode(res.body);
//update data value and UI
});
} else {
//there is error
setState(() {
error = true;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: AppLayout.getHeight(100),
automaticallyImplyLeading: false,
title: searchField(),
backgroundColor: Styles.background,
elevation: 0.0,
),
body: SingleChildScrollView(
child: Container(
alignment: Alignment.center,
child: data == null
? Container(
padding: EdgeInsets.all(20),
child: searching
? Text("Please wait")
: Text("Search any location")
//if is searching then show "Please wait"
//else show search peopels text
)
: Container(
child: searching
? showSearchSuggestions()
: Text("Find any location"),
)
// if data is null or not retrived then
// show message, else show suggestion
),
),
);
}
Widget showSearchSuggestions() {
List suggestionlist = List.from(data["data"].map((i) {
return SearchSuggestion.fromJSON(i);
}));
//serilizing json data inside model list.
return Column(
children: suggestionlist.map((suggestion) {
return InkResponse(
// onTap: () {
// //when tapped on suggestion
// print(suggestion.id); //pint student id
// },
child: GestureDetector(
onTap: () {
_sendDataBack(context);
},
child: SizedBox(
width: double.infinity, //make 100% width
child: Card(
child: Container(
decoration: BoxDecoration(color: Styles.background),
padding: EdgeInsets.all(15),
child: Text(
suggestion.name,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
);
}).toList(),
);
}
// get the text in the TextField and send it back to the FirstScreen
void _sendDataBack(BuildContext context) {
String textToSendBack = textFieldController.text;
Navigator.pop(context, textToSendBack);
}
Widget searchField() {
//search input field
return Container(
height: 50,
child: TextField(
controller: _controller,
autofocus: true,
style: Styles.textStyle,
decoration: InputDecoration(
hintStyle: TextStyle(color: Styles.colorDeepGrey),
hintText: "Search Location...",
prefixIcon: Icon(Icons.search),
suffixIcon: _controller.text.length > 0
? IconButton(
onPressed: () {
_controller.clear();
setState(() {});
},
icon: Icon(Icons.cancel, color: Colors.grey))
: null,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Styles.colorLightBlack.withOpacity(0.20),
width: 2,
),
borderRadius: BorderRadius.circular(4),
), //under line border, set OutlineInputBorder() for all side border
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Styles.primaryColor,
width: 1,
),
borderRadius: BorderRadius.circular(4),
), // focused border color
), //decoration for search input field
onChanged: (value) {
query = value; //update the value of query
getSuggestion(); //start to get suggestion
},
),
);
}
}
//serarch suggestion data model to serialize JSON data
class SearchSuggestion {
String id, name;
SearchSuggestion({required this.id, required this.name});
factory SearchSuggestion.fromJSON(Map<String, dynamic> json) {
return SearchSuggestion(
id: json["id"],
name: json["name"],
);
}
}
Sample Code NextPage Screen :
class NextPage extends StatefulWidget {
#override
_NextPageState createState() => _NextPageState();
}
class _NextPageState extends State<NextPage> {
int _currentStep = 0;
StepperType stepperType = StepperType.vertical;
String text = 'Text';
var _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Flutter Stepper Demo'),
centerTitle: true,
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Stepper(
type: stepperType,
physics: ScrollPhysics(),
currentStep: _currentStep,
onStepTapped: (step) => tapped(step),
onStepContinue: continued,
onStepCancel: cancel,
steps: <Step>[
//Form Pengirim
Step(
title: new Text('Location'),
content: Column(
children: <Widget>[
SizedBox(
height: 50,
child: TextField(
onTap: () {
_awaitReturnValueFromSecondScreen(context);
},
controller: _controller,
autofocus: true,
onChanged: (text) {
setState(() {});
},
style: Styles.textStyle,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: 'Location',
contentPadding:
EdgeInsets.only(left: 15, right: 15),
hintStyle: TextStyle(color: Styles.colorDeepGrey),
suffixIcon: _controller.text.length > 0
? IconButton(
onPressed: () {
_controller.clear();
setState(() {});
},
icon: Icon(Icons.cancel,
color: Colors.grey))
: null,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color:
Styles.colorLightBlack.withOpacity(0.20),
width: 2,
),
borderRadius: BorderRadius.circular(4),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Styles.primaryColor,
width: 1,
),
borderRadius: BorderRadius.circular(4),
),
),
),
),
],
),
isActive: _currentStep >= 0,
state: _currentStep >= 0
? StepState.complete
: StepState.disabled,
),
],
),
),
],
),
),
);
}
void _awaitReturnValueFromSecondScreen(BuildContext context) async {
// start the SecondScreen and wait for it to finish with a result
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DataAlamat(),
));
// after the SecondScreen result comes back update the Text widget with it
setState(() {
text = result;
});
}
tapped(int step) {
setState(() => _currentStep = step);
}
continued() {
_currentStep < 2 ? setState(() => _currentStep += 1) : null;
}
cancel() {
_currentStep > 0 ? setState(() => _currentStep -= 1) : null;
}
}
Pass the tapped item value to the next page via named parameter of other page class.
class ListPage extends StatelessWidget {
const ListPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return NextPage(value: index);
},
));
},
title: Text(index.toString()),
);
},
),
);
}
}
class NextPage extends StatelessWidget {
final int value;
const NextPage({Key? key, required this.value}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(value.toString()),
),
);
}
}
Example in ListView screen, you have a variable called List<String> listLocations. Your ListView widget be like:
ListView.builder(
itemCount: listLocations.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return SecondScreen(listLocations[index]);
},
)),
child: ...
);
}
}
And your SecondScreen is a StatefulWidget (well it is a Form screen, so it would be Stateful, not Stateless, use TextEditingController in Form widget):
import 'package:flutter/material.dart';
class SecondScreen extends StatefulWidget {
final String location;
SecondScreen(this.location, {Key? key}) : super(key: key);
#override
State<SecondScreen> createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
var _textEditingController = TextEditingController();
#override
void initState() {
_textEditingController.text = widget.location;
super.initState();
}
#override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container();
}
}
You need to pass the location value in init state, and don't forget to dispose it.

how to show a text field when a specific radio button is selected in flutter?

I want that when I choose home then a text field appears on the screen to input some information.
I wrapped the text field with Visibility but it didn't work.
Container(
margin: const EdgeInsets.only(top: 220,left:0),
child: RadioListTile(
title: const Text('home'),
value: place.home,
groupValue: selacted,
onChanged: (place? value) {
if(place.home==selacted) {
setState(() {
isVisible = true;
selacted= value;
});
}
}
),
),
Container(
margin: const EdgeInsets.only(top: 300,left:0),
child: Visibility(
visible:isVisible,
child:const TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
),
),
It seems you are comparing the previously selected value.
This should work:
setState(() {
_place = value;
_homeFieldVisible = value == Place.home;
});
Full code sample:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
enum Place { road, home, work }
class _HomePageState extends State<HomePage> {
Place? _place;
bool _homeFieldVisible = false;
void handleSelection(Place? value) {
setState(() {
_place = value;
_homeFieldVisible = value == Place.home;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
RadioListTile(
title: const Text('on the road'),
value: Place.road,
groupValue: _place,
onChanged: handleSelection,
),
RadioListTile(
title: const Text('at home'),
value: Place.home,
groupValue: _place,
onChanged: handleSelection,
),
if (_homeFieldVisible)
const TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
RadioListTile(
title: const Text('at work'),
value: Place.work,
groupValue: _place,
onChanged: handleSelection,
),
],
),
),
),
);
}
}
Your onChanged method should be changed to the following.
onChanged: (place? value) {
setState(() {
selacted = value;
if (place.home == selacted) {
isVisible = true;
}
});
}

TextEditingController not passing text into named parameters

I am really struggling to understand why my code isn't working. I'm trying to pass the text from two controllers into another widget with named parameters which writes to Firebase.
My "Test" button properly prints both _titleController.text and _descriptionController.text
TextButton(
onPressed: (){
print(_titleController.text); //works fine
print(_descriptionController.text); //works fine
},
child: Text('test')
),
However when I pass these into my next widget it's blank! If I hardcore strings into these parameters it works properly:
PushNewE3 (
changeTitle: _titleController.text, //does not work (empty)
changeDescription: _descriptionController.text, //does not work (empty)
)
Full code:
class CreateE3 extends StatefulWidget {
const CreateE3({Key? key}) : super(key: key);
#override
_CreateE3State createState() => _CreateE3State();
}
class _CreateE3State extends State<CreateE3> {
final _titleController = TextEditingController();
final _descriptionController = TextEditingController();
#override
void initState(){
super.initState();
_titleController.addListener(_printLatestValue);
}
#override
void dispose(){
_titleController.dispose();
super.dispose();
}
void _printLatestValue(){
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('So Frustrating'),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 800,
child: Column(
children: [
Text('Originator: **Add Current User**') ,
TextField(
maxLength: 40,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Change Title'
),
controller: _titleController,
onEditingComplete: (){
//_title = _titleController.text;
},
),
Padding(
padding: const EdgeInsets.fromLTRB(0,10,0,0),
child: TextFormField(
maxLines: 5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Detailed Description'
),
controller: _descriptionController,
),
),
TextButton(
onPressed: (){
print(_titleController.text); //successfully prints
print(_descriptionController.text); //successfully prints
},
child: Text('test')
),
PushNewE3 (
changeTitle: _titleController.text, //DOES NOT WORK (empty)
changeDescription: _descriptionController.text, //DOES NOT WORK (empty)
)
],
),
),
],
),
);
}
}
class PushNewE3 extends StatelessWidget {
final String changeTitle;
final String changeDescription;
PushNewE3({
required this.changeTitle,
required this.changeDescription
});
#override
Widget build(BuildContext context) {
// Create a CollectionReference called users that references the firestore collection
CollectionReference notificationsE3 = FirebaseFirestore.instance.collection('notificationsE3');
Future<void> pushNewE3() {
// Call the notifications CollectionReference to add a new E3 notification
return notificationsE3
.add({
//'originator': FirebaseAuth.instance.currentUser,
'changeTitle': changeTitle,
'changeDescription': changeDescription,
})
.then((value) => print("E3 Created"))
.catchError((error) => print("Failed to create E3: $error"));
}
return TextButton(
onPressed: (){
print('start:');
print(changeTitle);
print(changeDescription);
print('-end');
},
child: Text(
"Create E3",
),
);
}
}
EDIT:
I still don't understand why the above code doesn't work. I refactored my code into a single widget and now it's working. If anyone can explain why I would still appreciate understanding as there is clearly a gap in my knowledge.
If anyone in the future runs into the same problem here is the refactored code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'main.dart';
var global = 'blank';
class CreateE3 extends StatefulWidget {
const CreateE3({Key? key}) : super(key: key);
#override
_CreateE3State createState() => _CreateE3State();
}
class _CreateE3State extends State<CreateE3> {
final _titleController = TextEditingController();
final _descriptionController = TextEditingController();
#override
Widget build(BuildContext context) {
// Create a CollectionReference called users that references the firestore collection
CollectionReference notificationsE3 = FirebaseFirestore.instance.collection('notificationsE3');
Future<void> pushNewE3() {
// Call the notifications CollectionReference to add a new E3 notification
return notificationsE3
.add({
//'originator': FirebaseAuth.instance.currentUser,
'changeTitle': _titleController.text,
'changeDescription': _descriptionController.text,
})
.then((value) => print("E3 Created"))
.catchError((error) => print("Failed to create E3: $error"));
}
return Scaffold(
appBar: AppBar(
title: Text(_titleController.text),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 800,
child: Column(
children: [
Text('Originator: **Add Current User**') ,
TextField(
maxLength: 40,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Change Title'
),
controller: _titleController,
onChanged: (text){
setState(() {
});
},
),
Padding(
padding: const EdgeInsets.fromLTRB(0,10,0,0),
child: TextFormField(
maxLines: 5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Detailed Description'
),
controller: _descriptionController,
),
),
TextButton(
onPressed: (){
pushNewE3();
},
child: Text('SAVE')
),
],
),
),
],
),
);
}
}
in the onPressed To pass a value and show it, you have to use setState(() { _myState = newValue; });
Something like this
TextButton(
onPressed: (){
print(_titleController.text);
print(_descriptionController.text);
setState(() { _myNewText = _titleController.text; });
},
child: Text('test')
),
I'm not sure what are you trying to do exactly but here's what I did:
1 - add a local variable _title
2 - add this code to the onPressed function:
setState(() {
_title= _titleController.text;
});
This is the whole code :
class CreateE3 extends StatefulWidget {
const CreateE3({Key? key}) : super(key: key);
#override
_CreateE3State createState() => _CreateE3State();
}
class _CreateE3State extends State<CreateE3> {
final _titleController = TextEditingController();
final _descriptionController = TextEditingController();
String _title = 'So Frustrating';
#override
void initState(){
super.initState();
}
#override
void dispose(){
_titleController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_title),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 400,
child: Column(
children: [
Text('Originator: **Add Current User**') ,
TextField(
maxLength: 40,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Change Title'
),
controller: _titleController,
onEditingComplete: (){
//_title = _titleController.text;
},
),
Padding(
padding: const EdgeInsets.fromLTRB(0,10,0,0),
child: TextFormField(
maxLines: 5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Detailed Description'
),
controller: _descriptionController,
),
),
TextButton(
onPressed: (){
print(_titleController.text);
print(_descriptionController.text);
setState(() {
_title = _titleController.text;
});
},
child: Text('test')
),
],
),
),
],
),
);
}
}
.........................
so this is when you first start the app :
after changing the TextField and pressing the 'test button the title in the appbar change :

Navigator.pop() not refresh data from database

I am trying to make create data with localhost mysql in separate page with home and after that go back to home that contain list of data with Navigator.pop(context). the problem is when i've done add data, the page go back to home and new data not appear in list, but after i refresh debug the data appear. what should i do to get new data in list after create data?
main.dart
import "package:flutter/material.dart";
import "dart:async";
import 'package:http/http.dart' as http;
import 'dart:convert';
import "Detail.dart";
import "CreatePegawai.dart";
void main() {
runApp(new MaterialApp(
title: "CRUD PEGAWAI",
home: new Home(),
));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future<List> readData() async {
final response = await http.get("http://10.0.2.2/modelpegawai/read.php");
return json.decode(response.body);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("List Data Pegawai"),
leading: new Icon(Icons.home),
backgroundColor: Colors.blue[300],
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
onPressed: ()=>Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context)=> new CreatePegawai(),
)
),
),
body: new FutureBuilder<List>(
future: readData(),
builder: (context, snapshot) {
if (snapshot.hasError) {
print(snapshot.error);
}
return snapshot.hasData
? new ItemList(list: snapshot.data)
: new Center(
child: new CircularProgressIndicator(),
);
},
),
backgroundColor: Colors.yellow[200],
);
}
}
class ItemList extends StatelessWidget {
final List list;
ItemList({this.list});
#override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: list == null ? 0 : list.length,
itemBuilder: (context, i) {
return new Container(
padding: const EdgeInsets.all(10.0),
child: new GestureDetector(
onTap: ()=>Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context)=>new Detail(list:list, index:i)
)
),
child: new Card(
child: new ListTile(
title: new Text(
list[i]['nama'],
style: new TextStyle(fontSize: 20.0),
),
leading: new Icon(Icons.assignment_ind),
subtitle: new Text(
"Asal : ${list[i]['asalKota']}",
style: new TextStyle(fontSize: 16.0),
),
)),
));
});
}
}
createPegawai.dart
import "package:flutter/material.dart";
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
class CreatePegawai extends StatefulWidget {
#override
_CreatePegawaiState createState() => _CreatePegawaiState();
}
class _CreatePegawaiState extends State<CreatePegawai> {
DateTime date2;
TextEditingController controllerNIP = new TextEditingController();
TextEditingController controllerNama = new TextEditingController();
TextEditingController controllerTgl = new TextEditingController();
TextEditingController controllerAsalKota = new TextEditingController();
TextEditingController controllerDept = new TextEditingController();
TextEditingController controllerEmail = new TextEditingController();
TextEditingController controllerPass = new TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("Tambah Pegawai"),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: ListView(
children: <Widget>[
new Column(
children: <Widget>[
new Text(
"Form Tambah Pegawai",
style: new TextStyle(
fontSize: 20.0,
),
),
nip(),
nama(),
tgl(),
asalKota(),
kodeDept(),
email(),
pass(),
new Padding(
padding: const EdgeInsets.all(10.0),
),
tombol(),
],
),
],
),
));
}
Widget nip() {
return TextField(
controller: controllerNIP,
decoration: new InputDecoration(
hintText: "NIP 3 Angka",
labelText: "NIP",
),
);
}
Widget nama() {
return TextField(
controller: controllerNama,
decoration: new InputDecoration(
hintText: "Masukan Nama",
labelText: "Nama",
),
);
}
Widget tgl() {
return new Container(
child: DateTimePickerFormField(
controller: controllerTgl,
inputType: InputType.date,
format: DateFormat("dd-MM-yyyy"),
initialDate: DateTime(2019, 1, 1),
editable: false,
decoration:
InputDecoration(labelText: 'Date', hasFloatingPlaceholder: false),
onChanged: (dt) {
setState(() => date2 = dt);
},
),
);
}
Widget asalKota() {
return TextField(
controller: controllerAsalKota,
decoration: new InputDecoration(
hintText: "Masukan Kota Asal",
labelText: "Kota Asal",
),
);
}
Widget kodeDept() {
return TextField(
controller: controllerDept,
decoration: new InputDecoration(
hintText: "Dept",
labelText: "Departmen",
),
);
}
Widget email() {
return TextFormField(
controller: controllerEmail,
keyboardType: TextInputType.emailAddress, //KEYBOARD TYPENYA ADALAH EMAIL ADDRESS AGAR SYMBOL # DILETAKKAN DIDEPAN KETIKA KEYBOARD DI TAMPILKAN
decoration: InputDecoration(
labelText: "Email",
hintText: "email#provide.com",
),
);
}
Widget pass() {
return TextFormField(
controller: controllerPass,
obscureText: true, //membuat titik2 pada inputan/tidak keliatan text
decoration: InputDecoration(
labelText: "Password",
hintText: "Masukan password",
),
);
}
Widget tombol() {
return RaisedButton(
child: new Text("Tambah"),
color: Colors.blueAccent,
onPressed: () {
create();
Navigator.pop(context);
},
);
}
void create(){
var url = "http://10.0.2.2/modelpegawai/create.php";
var formatter = new DateFormat('yyyy-MM-dd');
String formatted = formatter.format(date2);
http.post(url, body:{
"nip": controllerNIP.text,
"nama": controllerNama.text,
"tgl": formatted,
"asalKota": controllerAsalKota.text,
"dept": controllerDept.text,
"email": controllerEmail.text,
"pass": controllerPass.text,
});
}
}
A simple trick to achieve your requirement is pass some data when poping from second screen.
// This is where you push to second screen from first screen
// Make sure you a method to get data from server
// And call that function when popped
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SecondScreen())).then(
(data){
if(data!=null && data){
getDataFromServer();
});
// This is where you are poping from second screen.
// Pass a bool whether you want refresh first screen or not.
Navigator.of(context).pop(true)
I Finally can solve this problem. the new data can show with add async and await in the createData() function like this
void create() async {
var url = "http://10.0.2.2/modelpegawai/create.php";
var formatter = new DateFormat('yyyy-MM-dd');
String formatted = formatter.format(date2);
await http.post(url, body:{
"nip": controllerNIP.text,
"nama": controllerNama.text,
"tgl": formatted,
"asalKota": controllerAsalKota.text,
"dept": controllerDept.text,
"email": controllerEmail.text,
"pass": controllerPass.text,
});
}