Flutter: Adding text from alert dialog to list view - android

I'm trying to add user input from the alert dialog to list view. Every time I run it, the alert dialog accepts input and the item list gets updated but the list view wont update. The state of the app wont change after I press OK on the alert dialog button. Please help me with this issue as I'm new to flutter.
Future<String> createAlertDialog(BuildContext context) {
//promise to return string
TextEditingController customController =
TextEditingController(); //new texteditingc object
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Enter URL: "),
content: TextField(
controller: customController,
),
actions: [
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(customController.text.toString());
},
)
],
);
});
}
#override
Widget build(BuildContext context) {
List item = List();
item=['HI'];
String temp;
return Scaffold(
appBar: AppBar(
title: Text("Shortie"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children:
item.map((element)=>Text(element)).toList(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
createAlertDialog(context).then((onValue) {
temp=onValue;
print(temp);
});
setState(() {
item.add(temp);
print(item);
});
},
tooltip: 'Add URL',
child: Icon(Icons.add),
),
);

You have to call setState() in order to update a Widget if you have new information.
Try changing your showDialog() to this:
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Enter URL: "),
content: TextField(
controller: customController,
),
actions: [
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
item.add(customController.text);
setState((){});
Navigator.of(context).pop();
},
)
],
);
});
That should add the element to the item list, update the widget and then pop. The timing between refresh and popping the dialog box is near instantaneous, so that should be smooth.
Furthermore, you might want to use ListView.builder, a class that will display a list that depends on the number of elements of the list of your choice.
With that said, changing the ListView to this could help in the future:
child: ListView.builder(
itemCount: item.length,
itemBuilder: (context, index) {
return Text('${item.index}'),
},
),

You should use await instate of then. And make item as class property. Your List is not updating because every time you called setState the build function rebuild and the value of item set to ['HI'] because of item=['HI'] this line.
Again when you use then function only the code inside of then function will execute when future will complete. That's why your setState called before your dialog finished.
Here I make some change of your code:
List item = List();
String temp;
Future<String> createAlertDialog(BuildContext context) {
//promise to return string
TextEditingController customController =
TextEditingController(); //new texteditingc object
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Enter URL: "),
content: TextField(
controller: customController,
),
actions: [
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(customController.text.toString());
},
)
],
);
});
}
#override
void initState() {
item = ['HI'];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Shortie"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children: item.map((element) => Text(element)).toList(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
temp = await createAlertDialog(context);
setState(() {
item.add(temp);
print(item);
});
},
tooltip: 'Add URL',
child: Icon(Icons.add),
),
);
}

You could use the provider package and communicate the AlertDialog with the ListView by using notifyListeners() and making the ListView a Consumer of the Provider data.
For more info about the package: https://pub.dev/documentation/provider/latest

Related

How to get value from alert Dialog box and set into a button in Flutter?

I have a Page, having a button. On click of this button alert dialog opens which has a list inside of it.
On tapping one of the list item, the alert dialog closes and the main page is there. Just as the dialog is closed, I want to set the selected item value into the button.
For this, this button widget should be rebuild, but I am unable to do so. How to achieve this functionality.
On my page, I'm calling this mainData() which makes a button widget on the screen.
Widget mainData() {
return RaisedButton(
child: Text('$tempVal'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context){
return AlertDialog(
content: StatefulBuilder(builder:
(BuildContext context,
StateSetter setState) {
_setState = setState;
return Column(
children: <Widget>[
Container(
child: //
// new SearchBar(mainData: mainData, list: list,),
list.length > 0
? ListView.builder(
itemCount: list.length,
shrinkWrap: false,
itemBuilder: (item, i){
return Card(
child: Column(
children: <Widget>[
Ink(
child: InkWell(
onTap: () {
setState(() {
tempVal = list[i].code;
});
},
child: ListTile(
title: Text(list[i].value),
),
),
),
],
),
);
},
)
),
],
);
},
),
);
}
);
},
);
}
How do I refresh the button widget after I have gotten the value from the list?
try to use the ontap method inside the listTile instead of the inkwell
ListTile(onTap: (){},title...

Use Provider to update Scaffold from a second screen

I want to have a Settings screen where I can choose a color to be returned to the first screen.
I can't get the first screen to update when the Setting screen is closed.
I'm using the Provider as a change notifier. But I can't see how to trigger the update of the first screen. The third button creates an event which updates the screen, but can this be done automatically?
What am I missing...?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
Color bgColor = Colors.yellow[100];
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: MyHomeScreen());
}
}
class MyHomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: Consumer<ColorModel>(builder: (context, colorModel, child) {
return Scaffold(
appBar: AppBar(title: Text('Thanks for your help :)')),
body: Container(
constraints: BoxConstraints.expand(),
color: bgColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Change background color on this screen'),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child:
Text('Button1', style: TextStyle(color: Colors.white)),
onPressed: () {
var result = Navigator.push(
context, MaterialPageRoute(builder: (context) => Screen2()));
print('>>> Button1-onPressed completed, result=$result');
},
),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child:
Text('Choose a colour', style: TextStyle(color: Colors.white)),
onPressed: () {
asyncButton(context);
print('>>> Screen1 Button-onPressed completed');
},
),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child:
Text('Now try me', style: TextStyle(color: Colors.white)),
onPressed: () {
colorModel.notifyListeners();
},
),
],
),
),
);
}),
);
}
void asyncButton(BuildContext context) async {
var result = await Navigator.push(
context, MaterialPageRoute(builder: (context) => Screen2()));
print('>>> asyncButton completed: result = $result');
bgColor = result;
}
}
class ColorModel with ChangeNotifier {
void updateDisplay() {
notifyListeners();
}
}
class Screen2 extends StatelessWidget {
int _value;
List<String> names = ['Red', 'Green', 'Blue'];
List<Color> colors = [Colors.red[100], Colors.green[100], Colors.blue[100]];
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: Scaffold(
appBar: AppBar(
toolbarHeight: 80,
backgroundColor: Colors.blue,
title: Center(child: Text('Screen2')),
),
body: Container(
constraints: BoxConstraints.expand(),
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Consumer<ColorModel>(builder: (context, colorModel, child) {
return DropdownButton(
value: _value,
hint: Text("Select a color"),
focusColor: Colors.lightBlue,
onChanged: (int value) {
Navigator.pop(context, colors[value]);
},
items: [
DropdownMenuItem(value: 0, child: Text(names[0])),
DropdownMenuItem(value: 1, child: Text(names[1])),
DropdownMenuItem(value: 2, child: Text(names[2])),
],
);
}),
],
),
),
),
);
}
}
Navigator.push is tricky to use with Provider. It causes a lot of "Could not find the correct Provider above this Navigator Widget" errors. I've explained why in this answer to a related question.
Here's a quick overview of your situation:
Provider Scope
Architecture in question code:
MaterialApp
> provider(Screen A)
> provider(Screen B)
Architecture in solution below:
provider(MaterialApp)
> Screen A
> Screen B
Here's your code sample, shortened up, working with Provider, updating the background color on Page 1 from the Page 2.
I've put comments throughout the code to explain changes.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// - global var removed -
// Color bgColor = Colors.yellow[100];
void main() {
runApp(ProviderApp());
}
class ProviderApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
/// Define your Provider here, above MaterialApp
return ChangeNotifierProvider(
create: (context) => ColorModel(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
home: ScreenA()
),
);
}
}
class ScreenA extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Thanks for your help :)')),
body: Container(
constraints: BoxConstraints.expand(),
//
// color: bgColor // - global var removed -
color: Provider.of<ColorModel>(context).bgColor,
// ↑ use your Provider state-stored value here ↑
//
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Change background color on this screen'),
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.green[600],
),
child: Text('Go Screen B', style: TextStyle(color: Colors.white)),
// Navigator.push returns a Future, must async/await to use return value
onPressed: () async {
var result = await Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ScreenB()));
// note that this context is not Screen A context, but MaterialApp context
// see https://stackoverflow.com/a/66485893/2301224
print('>>> Button1-onPressed completed, result=$result');
},
),
],
),
),
);
}
}
/// This is your state object. Store your state here.
/// Create this once and use anywhere you need. Don't re-create this unless
/// you want to wipe out all state data you were holding/sharing.
class ColorModel with ChangeNotifier {
// color is the state info you want to store & share
Color bgColor = Colors.yellow[100]; // initialized to yellow
/// Update your state value and notify any interested listeners
void updateBgColor(Color newColor) {
bgColor = newColor;
notifyListeners();
}
/// - removed - replaced with updateBgColor ↑
/*void updateDisplay() {
notifyListeners();
}*/
}
class ScreenB extends StatelessWidget {
// all fields in StatelessWidgets should be final
//final int value; // this value isn't needed
final List<String> names = ['Red', 'Green', 'Blue'];
final List<Color> colors = [Colors.red[100], Colors.green[100], Colors.blue[100]];
#override
Widget build(BuildContext context) {
/// Instantiating your model & giving it to Provider to should only happen once per
/// Widget Tree that needs access to that state. e.g. MaterialApp for this solution
/// The state object & Provider below was repeated & has been commented out / removed.
/// This was wiping out any previously stored state and creating a new Provider / Inherited scope
/// to all children.
/*return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ColorModel()),
],
child: ,
);*/
// - end of duplicate Provider removal -
return Scaffold(
appBar: AppBar(
title: Text('Screen2'),
),
body: Container(
alignment: Alignment.center,
child: Consumer<ColorModel>(builder: (context, colorModel, child) {
return DropdownButton(
//value: value, // this value isn't needed
hint: Text("Select a color"),
onChanged: (int value) {
colorModel.updateBgColor(colors[value]);
Navigator.pop(context, colors[value]);
},
items: [
DropdownMenuItem(value: 0, child: Text(names[0])),
DropdownMenuItem(value: 1, child: Text(names[1])),
DropdownMenuItem(value: 2, child: Text(names[2])),
],
);
}),
),
);
}
}

Exception caught by widgets library - Flutter

As I mentioned at the title, I got this error:
Exception caught by widgets library
Closure call with mismatched arguments: function '[]'
Receiver: Closure: () => Map<String, dynamic> from Function 'data':.
Tried calling: []("imageURL")
Found: []() => Map<String, dynamic>
I have been trying to use it to get data from firestore and show it on my app page. But I can't get the data from collection, especially for images. I referenced this tutorial from youtube. Even though I've done everything same but I couldn't handle it. Maybe bc of version. I'd be glad if you help me.
class _HomeState extends State<Home> {
PostService postService = new PostService();
Stream postStream;
//Stream postsStream;
Widget postsList() {
return SingleChildScrollView(
child: postStream != null
? Column(
children: <Widget>[
StreamBuilder(
//stream: postStream,
stream: postStream,
builder: (context, snapshot)
{
if(snapshot.data == null) return CircularProgressIndicator();
return ListView.builder(
padding: EdgeInsets.symmetric(horizontal:16.0),
itemCount: snapshot.data.docs.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return PostTile(
imgUrl: snapshot.data.docs[index].data['imageURL'],
title: snapshot.data.docs[index].data['postTitle'],
desc: snapshot.data.docs[index].data['postDesc'],
city: snapshot.data.docs[index].data['cityName'],
);
});
}),
],
): Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
),
);
}
#override
void initState() {
postService.getPostData().then((result) {
setState(() {
postStream = result;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Ana Sayfa'),
backgroundColor: Colors.amber,
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.group_rounded),
label: Text(''),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => KullaniciSayfasi()));
},
),
],
),
body: postsList(),
floatingActionButton: Container(
padding: EdgeInsets.symmetric(vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(
onPressed: () {
//Ekleme butonuna basıldığında
Navigator.push(context,
MaterialPageRoute(builder: (context) => CreatePost()));
},
child: Icon(Icons.add),
)
],
),
),
);
}
}
Code for post service
import 'package:cloud_firestore/cloud_firestore.dart';
class PostService{
Future<void> addData(postData) async{
FirebaseFirestore.instance.collection("posts").add(postData).catchError((e){
print(e);
});
}
getPostData() async{
return await FirebaseFirestore.instance.collection("posts").snapshots();
}
}
There was a breaking change on firebase plugins and many things have changed. E.g i see you're doing snapshot.data.docs[index].data['imageURL'] this has been changed to snapshot.data.docs[index].data()['imageURL']. Kindly check the docs for the updated API refrences

Flutter: How to show loading screen after the url is added?

I'm building a URL shortner app. I want to show a loading screen after the url is entered. This is my code. I'm a beginner to flutter. Please help me since this is my first app. The code is given below. As you can see the I'm using FutureBuilder so if the url list is empty it shows a corresponding message but I want it to disappear after the ok button of the alertdialog is pressed.
class _homePageState extends State<homePage> {
List userURL = List();
List item = List();
Future<List> getdata() async {
//JSON Parser
var url = 'https://api.shrtco.de/v2/shorten?url=${userURL.last}';
var respons = await http.get(url);
var result = jsonDecode(respons.body);
item.add(result['result']['short_link']); //dictionary parse
print(item);
return item;
}
createAlertDialog(BuildContext context) {
//method for alertdialog
//promise to return string
TextEditingController customController =
TextEditingController(); //new texteditingc object
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Enter URL: "),
content: TextField(
controller: customController,
),
actions: [
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
if (customController.text != null &&
customController.text != "") {
userURL.add(customController.text);
}
setState(() {});
Navigator.of(context).pop();
},
)
],
);
});
}
#override
Widget build(BuildContext context) {
String temp;
return Scaffold(
appBar: AppBar(
title: Text("Shortie"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: FutureBuilder(
future: getdata(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.sentiment_very_dissatisfied,
color: Colors.grey,
size: 80,
),
Text(
"No short links to display",
style: TextStyle(
color: Colors.grey[700],
fontSize: 15,
//fontWeight: FontWeight.bold
),
),
]));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.link),
title: Text(snapshot.data[index]),
subtitle: Text(userURL[index]),
onTap: () {
Share.share(
'Check out the short link I just shared with the application Shortie: ${snapshot.data[index]}',
subject: 'Shortie short link');
print(snapshot.data[index]);
},
);
},
);
}
},
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
createAlertDialog(context).then((onValue) {
temp = onValue;
print(temp);
});
You can make use of the connection state class of the FutureBuilder as follows:
FutureBuilder(
future: getdata(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(backgroundColor: Colors.blue);
} else {
return Container();
}
},
);
Also, on your button you need to call setState() to trigger the view reload, which in turn will again check the connectionState, if the async function is still in progress you will see the loading indicator, otherwise something you put in else

ListTile at Home screen is not updating with InheritedWidget

I'm getting started with flutter/dart and I'm trying to implement a simple note app using InheritedWidget and TextControllers, but when I add or edit some note it doesn't update the main screen. I printed the new notes list in console and it is updated with the addings and editings but is not updated in main screen, still showing the initial note list ({'title': 'someTitle1', 'text': 'someText1'}, ...).
main.dart :
void main() => runApp(NoteInheritedWidget(
MaterialApp(
title: 'Notes App',
home: HomeList(),
),
));
home screen scaffold body :
List<Map<String, String>> get _notes => NoteInheritedWidget.of(context).notes;
...
body: ListView.builder(
itemCount: _notes.length,
itemBuilder: (context, index) {
return Card(
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 7),
child: ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => NotePage(noteMode: NoteMode.Editing, index: index))
);
print(_notes);
},
trailing: Icon(Icons.more_vert),
title: _NoteTitle(_notes[index]['title']),
subtitle: _NoteText(_notes[index]['text']),
),
);
},
),
Add/Edit Note page :
enum NoteMode {
Adding,
Editing
}
class NotePage extends StatefulWidget {
final NoteMode noteMode;
final int index;
const NotePage ({this.noteMode, this.index});
#override
_NotePageState createState() => _NotePageState();
}
class _NotePageState extends State<NotePage> {
final TextEditingController _titleController = TextEditingController();
final TextEditingController _textController = TextEditingController();
List<Map<String, String>> get _notes => NoteInheritedWidget.of(context).notes;
#override
void didChangeDependencies() {
if (widget.noteMode == NoteMode.Editing) {
_titleController.text = _notes[widget.index]['text'];
_textController.text = _notes[widget.index]['title'];
}
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.noteMode == NoteMode.Adding ? 'Add Note' : 'Edit Note'
),
centerTitle: true,
backgroundColor: Colors.indigo[700],
),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
TextField(
controller: _titleController,
decoration: InputDecoration(
hintText: 'Note Title',
border: OutlineInputBorder(),
),
),
SizedBox(height: 20),
TextField(
controller: _textController,
maxLines: 20,
decoration: InputDecoration(
hintText: 'Note Text',
border: OutlineInputBorder(),
),
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
_NoteButton(Icons.save, 'Save', () {
final title = _titleController.text;
final text = _textController.text;
if (widget.noteMode == NoteMode.Adding) {
_notes.add({'title': title, 'text': text});
print(_notes);
} else if (widget.noteMode == NoteMode.Editing) {
_notes[widget.index] = {'title': title, 'text': text};
print(_notes);
}
Navigator.pop(context);
}),
_NoteButton(Icons.clear, 'Discard', () {
Navigator.pop(context);
}),
if (widget.noteMode == NoteMode.Editing)
_NoteButton(Icons.delete, 'Delete', () {
_notes.removeAt(widget.index);
Navigator.pop(context);
}),
],
),
],
),
),
),
);
}
}
InheritedWidget :
class NoteInheritedWidget extends InheritedWidget {
final notes = [
{'title': 'someTitle1', 'text': 'someText1'},
{'title': 'someTitle2', 'text': 'someText2'},
{'title': 'someTitle3', 'text': 'someText3'}
];
NoteInheritedWidget(Widget child) : super(child: child);
static NoteInheritedWidget of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<NoteInheritedWidget>();
}
#override
bool updateShouldNotify(NoteInheritedWidget old) {
return old.notes != notes;
}
}
Home screen after add a note :
HomeScreen
List of notes printed in console after add a note :
I/flutter (18079): [{title: someTitle1, text: someText1}, {title: someTitle2, text: someText2}, {title: someTitle3, text: someText3}, {title: NewAddNoteTitle, text: NewAddNoteText}]
I'm using Android Studio and a real device instead an emulator.
I can't find the error and if you have another way to do this 'update' please show me.
I found a solution using the onPressed method as async and then an empty setState, is there any problem for the code doing this?
code:
child: ListTile(
onTap: () async {
await Navigator.push(context,
MaterialPageRoute(builder: (context) => NotePage(noteMode: NoteMode.Editing, index: index))
);
setState(() {});
print(_notes);
},
...
floatingActionButton: FloatingActionButton(
onPressed: () async {
await Navigator.push(context,
MaterialPageRoute(builder: (context) => NotePage(noteMode: NoteMode.Adding))
);
setState(() {});
print(_notes.length);
print(_notes);
},

Categories

Resources